3

I have an ASP.NET program where i am downloading a file from web using DownloadFile method of webClient Class and the do some modifications on it. then i am Saving it to another folder with a unique name.When I am getting this error

The process cannot access the file 'D:\RD\dotnet\abc\abcimageupload\images\TempStorage\tempImage.jpg' because it is being used by another process

Can anyone tell me how to solve this.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Shyju
  • 214,206
  • 104
  • 411
  • 497

6 Answers6

6

Generally, I think your code should looking something like this.

WebClient wc = new WebClient();
wc.DownloadFile("http://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");
Joel Meador
  • 2,586
  • 2
  • 19
  • 24
4

I've had very good success using the tools from SysInternals to track which applications are accessing files and causing this kind of issue.

Process Monitor is the tool you want - set it up to filter the output to just files in the folder you're interested in, and you'll be able to see every access to the file.

Saves having to guess what the problem is.

Bevan
  • 43,618
  • 10
  • 81
  • 133
  • Another useful tool for debugging file locking issues is Unlocker, though it only works with x32 systems. The application is available at http://ccollomb.free.fr/unlocker/. – Mun Jan 17 '09 at 20:10
1

try the following, set your filestream to Asynchronus mode (3rd parameter)

FileStream myStream = File.Create(fileName, results.Length,FileOptions.Asynchronous);
//make sure you close the file
myStream.Write(results, 0, results.Length);
myStream.Flush();
myStream.Close();
myStream.Dispose();

if this fails reset the attributed of the file b4 you access it

File.SetAttributes(Server.MapPath(sendFilepath), FileAttributes.Normal);
Sadegh
  • 4,181
  • 9
  • 45
  • 78
0

Are you explicitly closing the file stream after you make your changes?

EBGreen
  • 36,735
  • 12
  • 65
  • 85
0

I dont know if this will solve your problem..

I got the exact same error when writing to a text file and then trying to open it afterwards.

It was solved by flushing the writer and then closing it after writing to the file..

Moulde
  • 3,438
  • 4
  • 29
  • 38
0

this may help....sorry its VB not C but hey...

This works

    Dim fs As FileStream = Nothing
    fs = File.Create("H:\test.txt")
    fs.Close()
    File.Delete("H:\test.txt")

This doesn't, give "file being used by another process" error

    File.Create("H:\test.txt")
    File.Delete("H:\test.txt")