2017-08-08 89 views
-1

我創建了循環來從我的datagridviews創建圖表圖像。我individualy做每一個圖像,然後我合併他們刪除文件循環錯誤

Image img = new Bitmap(1024, 1200); 
      Graphics g = Graphics.FromImage(img); 

      g.DrawImage(Image.FromFile("chart" + i + ".png"), new System.Drawing.Point(0, 100)); 

      g.DrawImage(Image.FromFile("chart2" + i + ".png"), new System.Drawing.Point(0, 600)); 

      img.Save("finalchart-" + i + ".png"); 

現在我想刪除這些個人圖表,只留下「finalchart」。所以我又做了一個循環來刪除單個圖表。

for (j = 1; j < columnCount; j++) 
     { 


      System.IO.File.Delete("chart" + j + ".png"); 
      System.IO.File.Delete("chart2" + j + ".png"); 
     } 

但是,當我開始我的計劃,我得到這個錯誤:

The process cannot access the file 'C:\Users\Frosty\Desktop\program\aproximator\program\program\bin\Debug\chart3.png' because it is being used by another process.

任何想法?謝謝

+3

你應該處理'圖像' –

+1

你必須處理你的對象。 (圖像img =新位圖(1024,1200)){使用(Graphics g = Graphics.FromImage(img)){//您的代碼}}' –

回答

0

只要img有一個參考,它會保持這些其他句柄。只需在最後處置它:

Image img = new Bitmap(1024, 1200); 
Graphics g = Graphics.FromImage(img); 
g.DrawImage(Image.FromFile("chart" + i + ".png"), new System.Drawing.Point(0, 100)); 
g.DrawImage(Image.FromFile("chart2" + i + ".png"), new System.Drawing.Point(0, 600)); 
img.Save("finalchart-" + i + ".png"); 
img.Dispose(); // like one commenter mentioned