c# - 从 Win32_TCPIPPrinterPort 检索主机地址时出现问题

标签 c# wmi

我在检索打印机端口地址时遇到了一个奇怪的问题。 当我获取 Win32_TCPIPPrinterPort 中的所有条目时,HostAddress 字段(应包含 IP 地址)通常为空/空,只有端口名称有值。更奇怪的是,如果某个特定端口未被任何打印机使用,那么 HostAddress 将具有正确的值。

C# 代码很简单,结果如下; IP_192.168.1.100, 打印机端口,

richTextBox1.Clear();
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher("root\\CIMV2",
    "SELECT * FROM Win32_TCPIPPrinterPort");
foreach (ManagementObject port in portSearcher.Get())
{
    richTextBox1.AppendText(
        String.Format("Name: {0} HostAddress: {1}",
            port["Name"],
            port["HostAddress"])
        );
}

我也在 WSH/VBS 中尝试过相同的操作,并看到了相同的行为。

最佳答案

我最终不得不重新访问它,并进行另一次尝试。我发现内置的 prnport.vbs 管理脚本没有问题 - 查看它我发现在建立其 WMI 连接时它有 oService.Security_.Priveleges.AddAsString "SeLoadDriverPrivilege"

C# 中的解决方案最终指定了 WMI ConnectionOptions 并将 EnablePrivileges 设置为 true。然后,对于未使用或正在使用的端口,HostAdress 不再为空。

ConnectionOptions connOptions = new ConnectionOptions();
connOptions.EnablePrivileges = true;

ManagementScope mgmtScope = new ManagementScope("root\\CIMV2", connOptions);
mgmtScope.Connect();

ObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort");
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mgmtScope, objQuery);

foreach (ManagementObject mo in moSearcher.Get())
{
    Console.WriteLine(String.Format("PortName={0} HostAddress={1}", mo["Name"], mo["HostAddress"]));
}

关于c# - 从 Win32_TCPIPPrinterPort 检索主机地址时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/726864/

相关文章:

python - 如何在 WMI 调用中分配变量?

windows - Powershell 删除配置文件脚本 - 错误检查不起作用

C# MySql.Data.MySqlClient 创建数据库失败

C# .net -> SQLite 错误 : Unable to open the database file

c# - 如何获取 N 个热 Observable<decimal> 实例的 "last"项的总和?

c# - C# 中的 WMI 查询在非英语机器上不起作用

c# - 枚举中的 "&"?

c# - 使用 C# .NET Core 3.1 返回具有属性的组成员的 Active Directory

c# - Powershell WMI 输出与 c# WMI 输出不匹配

windows - 获取Lun号和对应的名字——windows