I have the following function to handle an uploaded image.
It works fine on the first attempt (after restarting IIS), but on the second attempt I always get
The process cannot access the file because it is being used by
another process
Now, I do understand that somehow the file is kept open by IIS, but why does it happen if I have
newFile.Flush();
newFile.Close();
newFile.Dispose();
Here is the full function:
private void SaveFile(HttpPostedFile file, string path)
{
Int32 fileLength = file.ContentLength;
string fileName = file.FileName;
byte[] buffer = new byte[fileLength];
file.InputStream.Read(buffer, 0, fileLength);
FileStream newFile = new FileStream(path, FileMode.Create, FileAccess.Write);
try
{
newFile.Write(buffer, 0, buffer.Length);
}
catch { }
finally
{
newFile.Flush();
newFile.Close();
newFile.Dispose();
}
}
UPDATE:
After a few checks, I am sure there is nothing else locking the file but w3wp.exe which is the IIS process.
Something else must be keeping the file open – or perhaps the second call is made (on a separate thread) before the first call has returned.
Incidentally, you would be better writing the code like this: