2012-07-02 86 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

相關問題