tags:

views:

69

answers:

1

I implemented helper for showing thumbnails from here
Next to thumbnail, there is delete link which calls this controller

//
        // HTTP POST: /Photo/Delete/1
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id, string confirmButton)
        {
            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();
For 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?

Thanks in advance

+1  A: 

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.

Bryan Denny
I am aware that thumb generator uses the file, I thought maybe the File.Delete() has something to do with it?
ile
I don't know the rest of your code, but I'm assuming that your thumbnail gen is somehow opening a handle to your file (for example, using the Bitmap class). When you are done using the file to generate the thumbnail, you have to .close() the bitmap class (or whatever class is using the file) in order to be able to delete it.
Bryan Denny
what exactly do I have to close. In link i posted in my question there is a class Bitmap bitmap = new Bitmap(FilePath); But bitmap.Close() isn't working.
ile
@ile: Sorry, I meant bitmap.Dispose(). Look at my edited response, I think I might have found the problem.
Bryan Denny
WRONG: finally block will be always hit even if you "do a return" from try block!
Marek
@Marek: I didn't know that, I retract my statement then.
Bryan Denny