Reputation: 55
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
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
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
Reputation: 4048
The most likely answers would be that either:
Upvotes: 0