2017-03-03 90 views
-1

我試圖添加一個窗體的一部分到PDF的圖片,所以我使用PDFsharp,但我遇到的一個問題是,我將它添加到PDF文件後無法刪除圖片。C#刪除文件「在mscorlib.dll中發生類型'System.IO.IOException'的第一次機會異常」

這是我使用的代碼:

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

我錯過了一些東西明顯?
或者有更好的方法來做到這一點?

+0

不要使用這樣驚人的標題! –

+1

爲什麼你不能刪除它?你有例外嗎? –

+0

我唯一得到的是「在mscorlib.dll中發生了類型'System.IO.IOException'的第一次機會異常」 – Drago87

回答

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

要回答第二個問題「還是有更好的如何做到這一點?「

使用MemoryStream而不是文件可以解決此問題。它會提高性能。解決方法很糟糕,但性能改進很好。

MemoryStream可以作爲參數傳遞。這比擁有固定文件名更清潔。無論您在程序中傳遞文件名還是MemoryStream,它都沒有實際意義。

相關問題