2009-11-25 48 views
0

爲什麼我下載文件後無法刪除文件?下載後無法刪除文件

我得到這個錯誤:

file 'exfile.jpgg' because it is being used by another process.

這裏是我的代碼,

string file_name = "pic.jpg" 
WebClient client = new WebClient(); 
client.DownloadFile("http://picture.com/pic.jpg", file_name); 
client.Dispose(); 
client = null; 

pictureBox1.Image = Image.FromFile(File_Name); 
pictureBox1.Image = null; 

FileInfo MyFile = new FileInfo(File_Name); 
MyFile.Delete(); 
+1

在試圖刪除它之前,您是否正在對文件進行任何操作?如果是這樣,請發佈該代碼。 –

回答

5

您需要處置Image對象。

The file remains locked until the Image is disposed.

0

聽起來像是你需要首先關閉WebClient的,因爲它會對它鎖。也許使用

 
WebClient.Close() or WebClient.Dispose() 

希望這給你的提示和幫助, 最好的問候, 湯姆。

+1

或者使用using指令爲了不忘記使用(WebClient w = new WebClient())關閉/處理webclient: w.DownloadFile(「http://file.com/exfile.jpg」,「 exfile.jpg「); } – tobsen

+1

我不相信WebClient有一個Close方法嗎? – Dougc

+1

處置無效 – toms

0

你能展示一些更多的代碼嗎?好像如果你是從文件

WebClient Class

,你是不是關閉流/讀取器讀取。這將保留該文件,並且不允許您刪除。

+0

我試圖刪除文件,使用此: FileInfo MyFile = new FileInfo(@ exfile.jpg); MyFile.Delete(); 也許這個零件是錯誤的? – toms

+0

爲什麼不System.IO.Path.Delete(...)? – t0mm13b

+0

System.IO.Path'不包含'Delete'的定義 – toms