tags:

views:

13450

answers:

6

I have an ASPX program where i am downloading a file from the www 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 tellme how to solve this

A: 

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

EBGreen
Yes I am using file.Dispose() method
Shyju
If you're *manually* calling Dispose(), are you doing so within a finally block? It's usually better to use a "using" statement.
Jon Skeet
Post the relevant code please...
tvanfosson
+3  A: 

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
The try/finally/fooStream.Close(); is unneccessary - the using will do just that.
configurator
A: 

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
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
A: 

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
A: 

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);

A: 

Hi guys, 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")
Andyf