用C#打印到网络打印机

时间:2011-09-06 15:10:21

标签: visual-studio-2010 c#-4.0

我试图在VS2010中通过C#打印到网络服务器,但是在使用它时遇到了困难。如果我使用“打印”Verb insted它打印正常但只对默认打印机。我正在使用PrintTo Verb来尝试指定打印机。在我使用打印动词的情况下,在将默认打印机更改为其他打印​​机后,我成功地可以使用printto动词打印到我尝试打印的同一网络打印机。这是我目前使用的代码。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:2)

仅使用动词PrintTo和 使用双引号引用printerName

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