正确的方法删除实时服务器上的图像

时间:2012-07-02 09:31:45

标签: c# asp.net iis

我创建了一个从服务器删除图像的简单方法。

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

该方法在Visual Studio开发服务器上运行良好,但是当我在使用IIS的实时服务器上尝试时,我不断收到错误消息,说明资源正在使用中。它最终在大约10次尝试后起作用,但我买不起。

也许我需要“锁定”该文件才能在IIS上运行?

谢谢!

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:1)

在大多数情况下,看起来IIS上的文件被其他进程使用。最简单的解决方案是尝试在循环中删除文件,等待其他进程释放锁。不过,您应该考虑设置最大尝试次数,并在每次尝试之间等待几毫秒:

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

答案 2 :(得分:0)

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