C# PrintDocument.Print()引发Win32Exception

C# PrintDocument.Print()引发Win32Exception,c#,printing,printdocument,win32exception,printdialog,C#,Printing,Printdocument,Win32exception,Printdialog,我从以下代码中得到一个奇怪的异常: var printDialog = new PrintDialog(); printDialog.ShowDialog(); var printDocument = new PrintDocument { DefaultPageSettings = { Landscape = true, PrinterSettings = new PrinterSettings { PrinterName = printDialog.Pri

我从以下代码中得到一个奇怪的异常:

 var printDialog = new PrintDialog();
        printDialog.ShowDialog();

        var printDocument = new PrintDocument { DefaultPageSettings = { Landscape = true, PrinterSettings = new PrinterSettings { PrinterName = printDialog.PrintQueue.Name } } };

        var updateResult = new UpdateResult<Image>(UpdateType.Print) { Success = true };
        foreach (string location in fileLocation)
        {
            try
            {
                _printImage = Image.FromFile(location);
                printDocument.PrintPage += PrintRequest;
            }
            catch (Exception exception)
            {
               //various error handling code here
            }
        }
        printDocument.Print();
var printDialog=new printDialog();
printDialog.ShowDialog();
var printDocument=new printDocument{DefaultPageSettings={scape=true,PrinterSettings=new PrinterSettings{PrinterName=printDialog.PrintQueue.Name}};
var updateResult=newupdateresult(UpdateType.Print){Success=true};
foreach(fileLocation中的字符串位置)
{
尝试
{
_printImage=Image.FromFile(位置);
printDocument.PrintPage+=PrintRequest;
}
捕获(异常)
{
//这里有各种错误处理代码
}
}
printDocument.Print();
最后一行抛出一个Win32Exception,详细信息为“句柄无效”,根据msdn文档,应该抛出的唯一异常是printer not found。异常似乎是某种驱动程序/非框架异常

当我选择我的打印机(Lexmark T640,设置为直接打印到打印机端口)时,代码打印良好,但选择我可以访问的其他两台打印机(另一台T640或dell颜色)中的任何一台,代码将失败。 另外两台打印机设置为通过我们的中央打印服务器打印,但我认为这不会有任何区别。 有人能给我指点吗


编辑:只使用printDialog.PrintQueue.Fullname进行了尝试,其行为也没有什么不同。按预期替换垃圾打印机名称会引发InvalidPrinterException,表明它已找到打印机,但似乎失败。

尝试将目标打印机设置为默认打印机(如果尚未设置),并查看是否仍会发生此情况。

以@Matt为例。 我没有设法弄清楚到底是什么问题,很可能与我们网络的配置有关,但那不是我的事

相反,我使用了不同的方法,使用了CommonDialogClass.ShowPhotoPrintingWizard(),它是Interop.WIA的一部分,如下所示


这将过程移交给照片打印向导,此后我没有遇到任何问题。

我只有在打印多个文档时才遇到此异常。我的解决办法是增加


printDocument.Dispose()
printDocument.Print()之后

我也有同样的问题。更改默认打印机解决了问题,但这对我来说不是一个可用的解决方案,因为用户需要能够打印到他们机器上的任何打印机上,我不能期望他们在每次打印之前不断更改默认值。知道如何让PrintDocument正常工作吗?