0

Possible Duplicate:
The process cannot access the file because it is being used by another process

I have a PDF file in my application i want to delete that file. when I try to delete the file it give the error "The process cannot access the file because it is being used by another process."

The code is as follows

if (File.Exists(sDownloadFile))
             File.Delete(sDownloadFile);

How can I delete this file?

Community
  • 1
  • 1
Mathew Paul
  • 647
  • 3
  • 16
  • 36
  • what type of application did you used? – Ami Sep 15 '12 at 07:04
  • still not clear your question.you only post the delete fun.Before that what you doing in that file?How you opened that file? If may shared that file or not? can you post the source code? or at least post the fun for how you opened that file? – Ami Sep 15 '12 at 07:28
  • When i click a button to delete the file I just checks the file is existing and then deletes – Mathew Paul Sep 15 '12 at 07:30
  • This happens when i try to download the file and closes the window. and then clicks the delete button quickly say about after 2-3 seconds – Mathew Paul Sep 15 '12 at 07:31

1 Answers1

0

The reason of error is bit simple. you have open a file but not properly close it. the instance remain live in memory.

write .Close() and .Dispose() method to release memory.

sample code from here:

WebClient wc = new WebClient();
wc.DownloadFile("https://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");
FileStream fooStream;
using (fooStream = new FileStream("foo.png", FileMode.Open))
{
    // do stuff
}
File.Move("foo.png", "foo2.png");
Community
  • 1
  • 1
Ria
  • 10,237
  • 3
  • 33
  • 60