2016-11-20 66 views
0

我正在使用WinForms。在我的表单中,我有一个按钮可以打印目录中的所有tif图像。如果打印作业被取消或打印完成,我想告诉我的应用程序释放图像。我认为FileInfo可能是这里的问题。我怎样才能完成这项任务?当使用它完成应用程序时释放该文件

List<string> DocPathList = new List<string>(); 
    private int page; 

    private void btn_Print_Click(object sender, EventArgs e) 
    { 
     DirectoryInfo SourceDirectory = new DirectoryInfo(@"C:\image\Shared_Directory\Printing_Folder\"); 
     FileInfo[] Files = SourceDirectory.GetFiles("*.tif"); //Getting Tif files 


     foreach (FileInfo file in Files) 
     { 
      DocPathList.Add(SourceDirectory + file.Name); 
     } 

     printPreviewDialog1.Document = printDocument1; 
     printPreviewDialog1.Show(); 
    } 

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) 
    { 
      e.Graphics.DrawImage(Image.FromFile(DocPathList[page]), e.MarginBounds); 
      page++; 
      e.HasMorePages = page < DocPathList.Count; 
    } 

    private void printDocument1_BeginPrint(object sender, PrintEventArgs e) 
    { 
     page = 0; 
    } 

如果我添加这行代码它释放图像。它工作,如果我点击一次按钮。但是,如果我想按下打印按钮第二次printPreviewDialog1.Show();抛出一个错误:

Exception thrown: 'System.ObjectDisposedException' in System.Windows.Forms.dll

 using (var image = Image.FromFile(DocPathList[page])) 
     { 
      e.Graphics.DrawImage(image, e.MarginBounds); 
      page++; 
      e.HasMorePages = page < DocPathList.Count; 
     } 

例如,如果我取消打印,然后转到文件浏览,删除/重命名/修改这个文件我下面的错误。 目前我必须关闭我的应用程序,然后我可以修改tif文件。

enter image description here

回答

1

在任何情况下,你需要像你在你的编辑说明来包装你imageusing块,因为Image.FromFile()keep a lock on the file until the image is disposed

您看到的ObjectDisposedException来自printPreviewDialog,与加载图像无关。您可以...

(一)使用printPreviewDialog1.ShowDialog(this)而不是要显示一个对话框,模态(即,块输入,而对话框打开父窗口),关闭它

后,不会处置该对话框

或(b)使用printPreviewDialog.Show(this)来显示对话框非模态,像你现在这样做,但添加下面的回调:

private void printPreviewDialog1_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     // Don't close and dispose the form if the user is just dismissing it. Hide instead. 
     if (e.CloseReason == CloseReason.UserClosing) 
     { 
      e.Cancel = true; 
      printPreviewDialog1.Hide(); 
     } 
    } 
0

订阅EndPrint Event和删除文件呢?

从文档:

EndPrint event also occurs if the printing process is canceled or an exception occurs during the printing process.

+0

我可能没有明确,我只想告诉应用程序,我不不想再使用这些文档,所以我不会这个Windows错误:行动不能完成,因为该文件在另一个应用程序中打开。 – taji01

相关问题