簡體   English   中英

C#-枚舉遠程計算機上的網絡打印機

[英]C# - Enumerating network printers on remote machine

我正在編寫一個應用程序,以檢查來自打印服務器的網絡打印機是否已連接到遠程計算機,但是遠程部分遇到了問題...我正在使用System.Printing,並將遠程主機名/ IP地址通過'compID'變量。 我遇到的問題是代碼總是返回本地計算機而不是遠程計算機上的網絡打印機:

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連接的機器類型受到某種限制?

因此,我有一種解決方法,經過一些測試,看來可以很好地完成工作。 使用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標志列出所有每台計算機的連接,將其輸出到臨時文本文件,然后檢查文本文件中是否包含打印機名稱:

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");

我知道這可能不是解決問題的最佳方法,但它似乎可以在我所使用的環境中工作,因此我提供了答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM