2009-05-01 393 views
5

我在嘗試刪除圖像文件時出現問題。 我總是得到一個錯誤,說:IOExeption未處理。訪問被拒絕,因爲該文件正在被另一個進程使用。C#File.Delete,另一個進程正在使用的文件

我不知道可能是什麼過程以及如何解決它。

private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) 
     {    
      Album album = GetAlbum(comboBox1.SelectedIndex); 
      Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex);   

      txtPhotoPath.Text = Directory.GetCurrentDirectory() + "\\" + photo.SPath; 

      lblExtention.Text = photo.SExtention; 
      txtPhotoTitle.Text = photo.STitle; 
      pctrbFoto.Image = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr()); 
     } 

private void btnChangePhoto_Click(object sender, EventArgs e) 
{ 
      Album album = GetAlbum(comboBox1.SelectedIndex); 
      Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex); 

      File.Delete("Albums\\Images\\" + photo.STitle + foto.SExtention); 

      photo.SExtention = lblExtention.Text; 
      photo.STitle = txtPhotoTitel.Text; 
      Photo.SPath = txtPath.Text; 

      File.Copy(photo.SPath, "Albums\\Images\\" + photo.STitle + photo.SExtention); 

}

感謝, Vinzcent


感謝所有的幫助。

我用這個和它工作得很好,現在


你的過程是使用文件中的一個,你需要設置圖像null,則使用這樣的事情:

變種IMG =圖像。 FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath,150)),GetfHeight(photo.SPath,150),null,new IntPtr());

pctrbFoto.Image = img;

img = null;

GC.Collect();

回答

2

你的過程是使用文件中的一個,你需要設置圖像爲null 使用這樣的事情:

using(var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr())) 
    pctrbFoto.Image = img; 
6

我看的第一個區域是在你的GetPhoto方法中。你有沒有關閉的StreamReader?確保在刪除之前,如果您正在對文件執行任何類型的I/O,則首先關閉這些連接。 GetPhoto()方法有什麼作用?

3

首先,您需要確定您的應用程序或其他應用程序是否已打開文件。

您可以使用Mark Russinovich的Process Explorer查看哪個程序打開了特定的文件或目錄。它是每個程序員/ IT專業人員應該使用(或者至少知道)的Windows Sysinternals優秀實用程序系列的一部分。

你可以在這裏得到它:http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

+0

我同意。但我沒有看到顯示程序正在使用的選項。 – TamusJRoyce 2011-05-20 15:40:35

0

可以使用解鎖程序來告訴你什麼程序(一個或多個)具有文件鎖定

注:刪除鏈接到解鎖程序 - 包含惡意軟件。

+0

你也可以使用Process Explorer來告訴你哪個程序有一個文件被鎖定(http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) – Brian 2009-09-28 16:01:32

+0

就像一個註釋,解鎖軟件doesn不包含惡意軟件... – 2009-11-25 16:59:57

2

當您在comboBox3_SelectedIndexChanged中調用Image.FromFile時,或許在別處也可以調用Image對象。因此,您的程序正在使用該文件。

您需要在每次打開圖像時處理圖像。

1

當所有其他情況都失敗時,可以使用MoveFileEx在下次重新啓動時刪除該文件。

3

你在哪裏獲取縮略圖使用:

using(Image img = Image.FromFile(foto.SPath)) 
{ 
    pctrbPhoto. Image = img.GetThumbnailImage(
    GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), 
    GetfHeight(photo.SPath, 150), null, new IntPtr()); 
} 

代替,以確保源圖像佈置(閉合),當你完成它。

他們的方式,你從文件中加載圖像,直到垃圾收集器決定釋放它,這可能是一段時間。

使用FromFile加載的圖像保存從打開加載的文件。

0

...但是,如果你的應用程序上的Web託管計劃運行?您無法在共享服務器上運行任何軟件。

我試過用dispose()和其他選項,但是我不能刪除像Vinzcent這樣的文件。

Maldito IIS:@

相關問題