Unable to delete file (jpeg)
I implemented helper for showing thumbnails from here. Next to the thumbnail, there is a delete link which calls this controller:
// HTTP POST: /Photo/Delete/1
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, string confi开发者_开发问答rmButton)
{
var path = "~/Uploads/Photos/";
Photo photo = photoRepository.GetPhoto(id);
if (photo == null)
return View("NotFound");
FileInfo TheFile = new FileInfo(Server.MapPath(path + photo.PhotoID + ".jpg"));
if (TheFile.Exists)
{
photoRepository.Delete(photo);
photoRepository.Save();
TheFile.Delete();
}
else return View("NotFound");
return View();
}
If I disable showing thumbnails then the file is deleted. Otherwise it sends error:
System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\ilija\My Documents\Visual Studio 2008\Projects\CMS\CMS\Uploads\Photos\26.jpg' because it is being used by another process.
I also don't know if my file delete function is properly written. Searching on the net, I see everyone uses File.Delete(TheFile);
, which I'm unable to use and I use TheFile.Delete();
. When using File.Delete(TheFile);
I get following error:
Error 1 'System.Web.Mvc.Controller.File(string, string, string)' is a 'method', which is not valid in the given context C:\Documents and Settings\ilija\My Documents\Visual Studio 2008\Projects\CMS\CMS\Controllers\PhotoController.cs 109 17 CMS
Am I missing something here?
It's because, as it says, another process has gained a handle on your file, therefore you cannot delete it. In this case the thumbnail generator grabbed a handle of your file, preventing you from deleting it. You have to close all handles on a file in your program in order to delete it.
精彩评论