2017-04-13 55 views
0

,所以我做了一個簡單的項目中,當我點擊一個按鈕的圖片編輯從文件夾文件中獲取的圖像,但是當我想刪除包含圖像的文件夾,它給了我一個錯誤。代碼如下刪除文件夾,但是該進程無法訪問該文件,因爲正在使用

private void button1_Click(object sender, EventArgs e) 
    { 
     string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png"; 
     pictureEdit1.Image = Image.FromFile(pathx); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     string dir = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage"; 
     try { 
      if (Directory.Exists(dir)) 
      { 
       //////give me an error in here/////// 
       Directory.Delete(dir, true); 
      } 
      else 
      { 
       MessageBox.Show("folder not found"); 
      } 
     } 
     catch (Exception ex) 
      { 
      MessageBox.Show(ex.Message); 
     } 

    } 

enter image description here

這樣做的目的,是在我的主要項目中,高速緩存的目的。所以我從服務器應答到本地後從某個文件夾中獲取圖像。當我想關閉主項目,我需要清除緩存或文件夾

更新

這是更好的替代1或備用2(處置)

private void button1_Click(object sender, EventArgs e) 
    { 
     string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png"; 

     //alternate1 
     using (FileStream stream = new FileStream(pathx, FileMode.Open, FileAccess.Read)) 
     { 
      pictureEdit1.Image = Image.FromStream(stream); 
      //stream.Dispose(); 
     } 

     //alternate2 
     //Image img = new Bitmap(pathx); 
     //pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr()); 
     //img.Dispose(); 

    } 
+1

[IOException的可能重複:該過程,因爲它是被另一個不能訪問該文件「文件路徑」過程(http://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being) –

+0

也許是因爲你是顯示在它預覽窗口,因此它正在被訪問。如果正在使用它,你不能刪除它? – Icewine

+1

@chopperfield「問題」是GDI +圖像使文件保持打開狀態。處置它,你嘗試從一個MemoryStream –

回答

1

的文檔上System.Drawing.Bitmap(http://msdn.microsoft.com/en-us/library/0cbhe98f.aspx)說:

該文件保持鎖定,直到位圖處置。

要解決這個問題,應更換這行:

pictureEdit1.Image = Image.FromFile(pathx); 

有了這個:

Image img = new Bitmap(pathx); 
pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr()); 
img.Dispose(); 

這應該加載位圖只有足夠長的時間來創建圖像的縮略圖用於PictureBox控件,然後立即處理它,釋放對文件的鎖定,但仍然在屏幕上顯示圖像。

希望這會有所幫助!

編輯:下面是使用,做同樣的事情用版本:

using (Image img = new Bitmap(pathx)) { 
    pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr()); 
} 
+0

喜lusid刪除文件或簡單地讀取該文件作爲一個byte [],並建立圖像之前,它工作正常。但我想用'使用(的FileStream流=新的FileStream(pathx,FileMode.Open,FileAccess.Read)){stream.dispose}'是一樣問現在IAM? – chopperfield

+0

實際上,** **使用C#中的語句將自動調用Dispose您使用的是塊結束時,在對象上,這樣你就不會使用** **需要的Dispose()**在這兩種情況下,如果你使用** 。有了這個說法,我個人不會在這裏使用FileStream,如果你所要做的只是將數據加載到內存中顯示,但你可以。 – Lusid

+0

從你說的是,當使用IAM'using'語句來顯示iamge,其使用內存進行顯示,而是用位圖不使用的內存。是嗎?但在塊'使用'結束時自動調用處理。所以它不應該使用內存來顯示..糾正我,如果我錯了 – chopperfield

相關問題