ttante
ttante

Reputation: 55

C# Can't Access File Because It Is Being Used By Another Process

This is my MVC controller to upload an image. I'm trying to check if the file exists, then deleting the old one and saving the new one if it does. I get the error at System.IO.File.Delete() telling me the file is in use already, but I can't figure out where I left it open and how I might close it.

[HttpPost]   
public ActionResult UploadImage(int? id, HttpPostedFileBase file, EmployeeViewModel employee)
{
    Employee employeeData = db.Employees.Find(id);
    if (file != null && file.ContentLength > 0)
    {
        // Assemble File Path/Extension String
        string[] fileSplit = file.FileName.Split('.');
        string extension = fileSplit[1];
        var fileNameNew = "employeeImage-" + id + "." + extension;
        var path = Path.Combine(Server.MapPath("~/Content/employeeImages/"), fileNameNew);

        var fileExists = System.IO.File.Exists(path);

        if (fileExists)
        {
            System.IO.File.Delete(path);
            file.SaveAs(path);
        }
        else
        {
            file.SaveAs(path);
        }

    }
    return RedirectToAction("Edit", new { id = id });
}

Upvotes: 1

Views: 723

Answers (3)

Igor
Igor

Reputation: 62298

There is probably a (web) method (like a GET request) or other code that retrieves the image (not the url) that leaves it open as a stream.

Upvotes: 1

ttante
ttante

Reputation: 55

Since I couldn't find the issue with my POST request, I realized it had to be in the GET request that was taking me to that page. Turns out I was calling Image.FromFile() and not closing it in that GET request.

Upvotes: 0

strickt01
strickt01

Reputation: 4048

The most likely answers would be that either:

  • The file is located on a network share and someone else is genuinely using it (is it a virtual directory?).
  • IIS/ your web server is locking the file (see Does IIS 6/7 lock image files whilst they're being served?
  • You are uploading the same file as you are writing to (apologies if this sounds patronising but you need to cover all options!)

Upvotes: 0

Related Questions