tags:

views:

363

answers:

4

Hey

Why can't I delete files after downloading file

I get error:

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

Edit: (Here is more code)

                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();
A: 

Sounds like you need to close the WebClient first as it would have a lock on it. Perhaps using

WebClient.Close() or WebClient.Dispose()

Hope this gives you the hint and helps, Best regards, Tom.

tommieb75
Or use the using directive in order to not forget to close/dispose the webclient: using (WebClient w = new WebClient()) {w.DownloadFile("http://file.com/exfile.jpg", "exfile.jpg");}
tobsen
I don't believe WebClient has a Close method?
Dougc
Dispose does not help
toms
@tobsen: Agreed! :D
tommieb75
A: 

Can you show some more code. Seems like if you were reading from the file as

WebClient Class

That you are not closing the stream/reader. This will hold onto the file, and will not allow you to delete.

astander
I am trying to delete files using this:FileInfo MyFile = new FileInfo(@exfile.jpg);MyFile.Delete();Maybe this part is wrong ?
toms
Why not System.IO.Path.Delete(...)?
tommieb75
System.IO.Path' does not contain a definition for 'Delete'
toms
System.IO.File contains Delete
phsr
+2  A: 

You can use ProcessExplorer to check who has unclosed hande to this file.

Pawel Lesnikowski
+4  A: 

Dispose Image object.

The file remains locked until the Image is disposed.