0

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

    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 上工作?

谢谢!

4

3 回答 3

1

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);
                }
            }
        }
    }
于 2012-07-02T13:55:31.003 回答
1

尝试这个

FileInfo myfileinf = new FileInfo(deletePath);
myfileinf.Delete();
于 2012-07-02T09:37:21.500 回答
0
String filePath = string.Empty;
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);    
filePath = Server.MapPath("../Images/gallery/") + filename;
System.IO.File.Delete(filePath); 
于 2012-07-02T11:06:41.740 回答