C# 删除文件 "A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll"

C# Deleting File "A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll"

我正在尝试将部分表格的图片添加到 PDF,因此我使用的是 PDFsharp,但我遇到的问题之一是我无法在将图片添加到 PDF 后将其删除PDF 文件。

这是我正在使用的代码:

private void button12_Click(object sender, EventArgs e)
{
    string path = @"c:\Temp.jpeg";
    Bitmap bmp = new Bitmap(314, this.Height);
    this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
    bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

    GeneratePDF("test.pdf",path);
    var filestream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
    filestream.Close();
    if (File.Exists(path))
    {
        File.Delete(path);
    }
}

private void GeneratePDF(string filename, string imageLoc)
{
    PdfDocument document = new PdfDocument();

    // Create an empty page or load existing
    PdfPage page = document.AddPage();

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(page);
    DrawImage(gfx, imageLoc, 50, 50, 250, 250);

    // Save and start View
    document.Save(filename);
    Process.Start(filename);
}

void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
    XImage image = XImage.FromFile(jpegSamplePath);
    gfx.DrawImage(image, x, y, width, height);
}

FileStream 在那里是因为我试图确保它已关闭,如果那是问题所在。 这是我获得将图片写入 PDF 的代码 overlay-image-onto-pdf-using-pdfsharp and this is where I got the code to make a picture of the form capture-a-form-to-image

我是不是漏掉了什么明显的东西?
或者有更好的方法吗?

如果您阅读 System.IO.IOException 的详细信息,它会告诉您

the file cannot be accessed because it is used by another process.

仍在使用您的图像的进程是这个不错的对象:

XImage image = XImage.FromFile(jpegSamplePath);

解决方案是在将图像绘制为 PDF 后对其进行处理:

void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
    XImage image = XImage.FromFile(jpegSamplePath);
    gfx.DrawImage(image, x, y, width, height);

    image.Dispose();
}

现在异常消失了……就像你的文件一样……

编辑

一个更优雅的解决方案是使用 using 块,这将确保在您完成文件后调用 Dispose()

void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
    using (XImage image = XImage.FromFile(jpegSamplePath))
    {
        gfx.DrawImage(image, x, y, width, height);
    }
}

回答第二个问题"Or is there a better way to do this?"

使用 MemoryStream 而不是文件可以解决这个问题。它会提高性能。解决方法不好,但性能改进很好。

MemoryStream 可以作为参数传递。这比有一个固定的文件名更干净。无论您在程序中传递文件名还是 MemoryStream,都没有实际区别。