2012-07-02 37 views
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上工作?

谢谢!

+2

为什么你捕捉异常,只是为了抛出它们?另外,最好只做一个'throw;'而不是'throw ex;',这样保持原始堆栈跟踪。 –

+0

我总是处理外层的异常(即调用方法)。所以这个异常就会被抛出,并以任何称为它的方法被捕获。 – TheGateKeeper

+1

如果您删除了try/catch,那么异常仍会传播到上一级。只是一个'catch(Exception ex){throw ex; }'除了破坏原始堆栈跟踪外,没有任何用处。 –

回答

1

试试这个

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

不知道File.Delete和这个之间有什么区别,但是这个很好用! – TheGateKeeper

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

你和我的区别究竟是什么?哟如何假设我正在使用fileUpload控件? – TheGateKeeper

+0

很难这样说,你可能需要显示你用来上传文件的代码。我的代码只是删除该文件,如果找到.. – Learning

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

也纳入我的解决方案。 – TheGateKeeper

相关问题