Reputation: 89
I am attempting to print to a network servia via C# in VS2010 but have run into difficulties getting it to work. If I use the "print" Verb insted it prints fine but only to the default printer. I am using the PrintTo Verb to try and specify a printer. In my case using print verb I successfully can print to the same network printer that I am trying to print to using the printto verb after I change my default printer to a different printer. Here is the code I am currently using. Any help would be greatly appreciated.
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);
}
}
Upvotes: 5
Views: 6216
Reputation: 41
only use verb PrintTo and use the double quotes to quote the printerName
processStartInfo.Verb = "PrintTo";
processStartInfo.Arguments = "\"" + printerName + "\"";
Upvotes: 4