TheGateKeeper
TheGateKeeper

Reputation: 4530

Proper way to delete an image on a live server

I created a simple method that deletes an image from the server.

    public static void deleteImage(string deletePath)
    {
        if (!File.Exists(deletePath))
        {
            FileNotFoundException ex = new FileNotFoundException();
            throw ex;
        }

        try
        {
            File.Delete(deletePath);
        }
        catch (IOException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

The method works great on the Visual Studio development server, but when I try it out on the live server that uses IIS I keep getting an error saying the resource is in use. It eventually works after about 10 attempts but I can't afford this.

Maybe I need to "lock" the file for this to work on IIS?

Thanks!

Upvotes: 0

Views: 844

Answers (3)

Marek Musielak
Marek Musielak

Reputation: 27142

It looks like the file on the IIS is used by some other process in most cases. The simplest solution is to try to remove the file in a loop waiting for the other process to release the lock. Still, you should consider to set the maximum number of tries and to wait for couple of miliseconds between each try:

    public static void DeleteImage(string filePath, int maxTries = 0) // if maxTries is 0 we will try until success
    {
        if (File.Exists(filePath))
        {
            int tryNumber = 0;

            while (tryNumber++ < maxTries || maxTries == 0)
            {
                try
                {
                    File.Delete(filePath);
                    break;
                }
                catch (IOException)
                {
                    // file locked - we must try again

                    // you may want to sleep here for a while
                    // Thread.Sleep(10);
                }
            }
        }
    }

Upvotes: 1

Learning
Learning

Reputation: 20031

String filePath = string.Empty;
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);    
filePath = Server.MapPath("../Images/gallery/") + filename;
System.IO.File.Delete(filePath); 

Upvotes: 0

Rab
Rab

Reputation: 35582

try this

FileInfo myfileinf = new FileInfo(deletePath);
myfileinf.Delete();

Upvotes: 1

Related Questions