Search code examples
asp.net-mvcfilestreamdisposeaccess-deniedbinarywriter

How do I close the filestream after creating a file or otherwise create access to the newly created file?


I'm saving a canvas image to the server using FileStream. It works fine the first time, but if the user visits the page again during the same session (without closing the browser) it throws the error "The process cannot access the file 'C:\inetpub\wwwroot\CarmelFinancialWeb\Contracts\MyUniqueImageFileName.png' because it is being used by another process." I tried to use close and dispose on the FileStream, but this is still occurring

Process: - User goes to AssignContract page, signs in the canvas, clicks the save button. - Image is saved to the file - User hits the save button again (even after waiting a few minutes) - Error message saying file is used by another process.

[AuthorizeAdmin]
    [HttpPost]
    public ActionResult AssignContract(string ID, ModelContract tempCurrentContract, string imageData)
    {
        try
        {
            if (imageData != null)
            {
                string fileName = "MyUniqueImageFileName.png";
                string fileNameWitPath = Path.Combine(Server.MapPath("~/Contracts"), fileName);

                using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        byte[] data = Convert.FromBase64String(imageData);
                        bw.Write(data);
                        bw.Close();
                        bw.Dispose();
                    }
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
...

Update

Haven't had any feedback on this. Anyone have a suggestion on how to prevent the file from being locked or how to unlock the file? Thank you.


Solution

  • The problem seems to be the file is locking each time I access the image to output it to another process. So for every instance where I access it:

    System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/Contracts/MyUniqueImageFileName.png"));
    

    I had to dispose of the image:

    image.Dispose();
    

    I did notice if I waited a few minutes and tried to save a new image, it was not locked. So maybe the Dispose function happens automatically after a period of time? If anyone knows that or has a way to unlock all files before writing a new one, I'd be interested in how that's done.