Saving the downloaded file - the process cannot access

I have the following function to handle an uploaded image.

It works fine on the first try (after restarting IIS), but on the second try I always get

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

Now I understand that somehow the file remains open by IIS, but why does this 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 several checks, I am sure that there is nothing blocking the file, but w3wp.exe , which is an IIS process.

+4
source share
1 answer

Something else should keep the file open - or perhaps the second call is made (in a separate thread) until the first call returns.

By the way, you better write code as follows:

 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); using (FileStream newFile = new FileStream(path, FileMode.Create, FileAccess.Write)) { newFile.Write(buffer, 0, buffer.Length); } } 
0
source

All Articles