应用程序使用完后释放文件

Release the file when application is done using it

我正在使用 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;
        }

例如,如果我取消我的打印,然后转到文件探索 delete/rename/modify 这个文件,我会出现以下错误。 目前我必须关闭我的应用程序然后我才能修改 tif 文件。

订阅 EndPrint Event 并删除那里的文件?

来自文档:

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

在任何情况下,您都需要将 image 包裹在 using 块中,就像您在编辑中描述的那样,因为 Image.FromFile()keep a lock on the file until the image is disposed

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

(a) 改为使用 printPreviewDialog1.ShowDialog(this) 以模态方式显示对话框(即,在对话框打开时阻止对父 window 的输入),关闭后不会处理对话框

或者,(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();
        }
    }