2011-09-06 126 views
4

我試圖通過VS2010中的C#打印到網絡servia,但遇到困難讓它工作。如果我使用「打印」動詞insted它打印罰款,但只有默認打印機。我正在使用PrintTo Verb來嘗試指定打印機。在我使用打印動詞的情況下,我成功地可以打印到我嘗試打印到使用printto動詞的相同網絡打印機後,將默認打印機更改爲另一臺打印機。這是我目前使用的代碼。任何幫助將不勝感激。在C#中打印到網絡打印機

private string FindPrinter(string printerName) 
    { 
     string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName); 
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); 
     ManagementObjectCollection printers = searcher.Get(); 

     foreach (ManagementObject printer in printers) 
     { 
      if (!String.IsNullOrEmpty(printer.Properties["PortName"].Value.ToString())) 
      { 
       return printerName = string.Format(@"\\{0}\{1}", printer.Properties["PortName"].Value.ToString(), printerName); 
      } 
     } 

     return printerName; 
    } 

    private void Print(string fileName, string printerName) 
    { 
     PrinterSettings ps = new PrinterSettings(); 
     ps.PrinterName = printerName; 
     if (ps.IsValid) 
     { 
      try 
      { 
       ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName); 
       using (PrintDialog pd = new PrintDialog()) 
       { 
        pd.ShowDialog(); 

        printerName = this.FindPrinter(pd.PrinterSettings.PrinterName); 
        if (printerName.IndexOf(@"\\") == 0) 
        { 

         processStartInfo.Verb = "PrintTo"; 
         processStartInfo.Arguments = printerName; 
        } 
        else 
        { 
         processStartInfo.Verb = "print"; 
        } 
       } 

       processStartInfo.CreateNoWindow = true; 
       processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

       Process printProcess = new Process(); 
       printProcess.StartInfo = processStartInfo; 
       bool printStarted = printProcess.Start(); 
       MessageBox.Show(string.Format("{0} printed to {1}", fileName, printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString(), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
     } 
     else 
     { 
      MessageBox.Show(string.Format("{0} printer does not exist. Please contact technical support.", printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

回答

2

只用動詞PrintTo和 使用雙引號來引用PRINTERNAME

processStartInfo.Verb = "PrintTo"; 
processStartInfo.Arguments = "\"" + printerName + "\"";