Question

I made a system where user can upload a file (image) to a server and server saves it. All is good, but when I want to delete the files uploaded by user, I get an exception saying:

the process cannot access the file because it is being used by another process

This is the code for saving the file:

HttpFileCollection files = httpRequest.Files;

for (int i = 0; i < files.Count; i++) {
    var postedFile = files[i];

    // I tried this one before, but I read that I should .Dispose() files, therefore
    // I settled to the other, uncommented solution (however, both of them do the same thing)
    //postedFile.SaveAs(filePath);
    using (FileStream fs = File.Create(filePath)) {
        postedFile.InputStream.CopyTo(fs);
        postedFile.InputStream.Close();
        postedFile.InputStream.Dispose();
        fs.Dispose();
        fs.Close();
    }
}

The deleting of files is quite simple. In a method called Delete, I call this method:

...
File.Delete(HttpContext.Current.Server.MapPath(CORRECT_PATH_TO_FILE));
...

Any suggestions on how to solve this?

Thanks

Was it helpful?

Solution

Just as Michael Perrenoud suggested me in the comment to my main question, I was also opening the file in another class and not disposing it when done with working with it. Problem is therefore solved. Thanks!

OTHER TIPS

Where are you trying the file delete method? As part of the loop? If so, it is natural to have it locked. If outside of the loop, then it is a different problem (perhaps not garbage collected yet?).

To avoid the loop problem, gather a list of locations you are going to delete (declare outside of the loop, can be populated within) and then delete in another "clean up" loop (another method is even better for reusability).

NOTE: Close() before Dispose() not the other way around. You actually do not have to do both, as Dispose() should always handle making sure everything is clean (especially in .NET framework uses of IDisposable), but I don't see any harm in Close() followed by Dispose().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top