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