【问题标题】:C# Deleting File "A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll"C# 删除文件“在 mscorlib.dll 中发生‘System.IO.IOException’类型的第一次机会异常”
【发布时间】:2017-07-23 05:21:04
【问题描述】:

我正在尝试将部分表单的图片添加到 PDF,因此我使用的是 PDFsharp,但我遇到的一个问题是,在将图片添加到 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 的代码的地方,也是我获得制作表格 capture-a-form-to-image 的图片的代码的地方

我错过了什么明显的东西吗?
或者有更好的方法吗?

【问题讨论】:

  • 不要用这么惊人的标题!
  • 为什么删不掉?你有例外吗?
  • 我唯一得到的是“在 mscorlib.dll 中发生了“System.IO.IOException”类型的第一次机会异常”
  • @LeiYang 什么是好标题?
  • 是你的应用程序不工作,而不是 C#。

标签: c# image pdf delete-file pdfsharp


【解决方案1】:

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

无法访问该文件,因为它被另一个进程使用。

仍在使用您的图像的过程是这个漂亮的对象:

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);
    }
}

【讨论】:

    【解决方案2】:

    回答第二个问题“或者有更好的方法吗?”

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

    MemoryStream 可以作为参数传递。这比使用固定文件名更干净。在程序内部传递文件名或 MemoryStream 并没有实际区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多