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 });
}