C# - 枚举远程计算机上的网络打印机

时间:2013-05-03 12:53:08

标签: c# system.printing printqueue

我正在编写一个应用程序来检查打印服务器中的网络打印机是否连接到远程计算机,但是远程部件出现问题...我正在使用System.Printing并传入远程主机名/ IP通过'compID'变量进行寻址。我遇到的问题是代码总是返回我的LOCAL机器而不是远程机器上的联网打印机:

EnumeratedPrintQueueTypes[] compEnumerationFlags = { EnumeratedPrintQueueTypes.Connections };

PrintServer compPrinters = new PrintServer("\\\\" + compID);
PrintQueueCollection printQueuesOnComputer = compPrinters.GetPrintQueues(compEnumerationFlags);

List<string> compPrinterList = new List<string>();

foreach (PrintQueue printer in printQueuesOnComputer)
    {
        compPrinterList.Add(printer.Name);
    }

string csv = string.Join("\n", compPrinterList.ToArray());
Microsoft.VisualBasic.Interaction.MsgBox(csv);

原谅那里最乱的一点,但这对我来说只是一个快速而又肮脏的方式,看看目前的结果是什么。

奇怪的是,如果我将'compID'变量更改为我们的实际打印服务器并将标志从“Connections”更改为“Shared”,则代码会成功返回打印服务器中的所有共享打印机。

所有这些都是作为我们域名的管理员运行的,因此希望这不是问题。有什么简单的我可以忽略或者我可以用PrintServer连接的机器类型有某种限制吗?

1 个答案:

答案 0 :(得分:0)

所以我有一个解决方法似乎在经过一些测试后做得很好。打印机将使用rundll32 printui.dll,PrintUIEntry /ga /c\\%computername% /n\\%printserver%\%printername%

在某个点连接到机器

在我导入printui.dll的应用程序中:

[DllImport("printui.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern void PrintUIEntryW(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow);

然后我使用远程机器上的/ge标志列出所有每台机器的连接,将其输出到临时文本文件,然后检查文本文件中是否包含打印机名称:< / p>

PrintUIEntryW(IntPtr.Zero, IntPtr.Zero, "/c \\\\" + compID + " /ge /q /f c:\\temp\\printers.txt", 0);

string file = File.ReadAllText("c:\\temp\\printers.txt");
if (file.Contains(printerID))
{
    exist = true;
}
File.Delete("c:\\temp\\printers.txt");

我知道这可能不是最好的方法,但它似乎在我操作的环境中工作,所以我提供这个作为答案。