Shyju
Shyju

Reputation: 218882

Cant Access File because it is being used by another process

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.

Upvotes: 3

Views: 65830

Answers (6)

kyri
kyri

Reputation:

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

Upvotes: 1

Andyf
Andyf

Reputation:

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

Upvotes: 0

Moulde
Moulde

Reputation: 3506

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..

Upvotes: 0

Bevan
Bevan

Reputation: 44327

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.

Upvotes: 4

user1976
user1976

Reputation:

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

Upvotes: 6

EBGreen
EBGreen

Reputation: 37820

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

Upvotes: 0

Related Questions