2012-02-29 72 views
1

處理文件(打開)是一項特別容易出錯的活動。打開文件時處理錯誤的最佳方法

如果你要編寫一個函數來做到這一點(雖然微不足道),那麼在處理錯誤時寫入它的最好方法是什麼?

以下是好嗎?

if (File.Exists(path)) 
{ 
    using (Streamwriter ....) 
    { // write code } 
} 

else 
// throw error if exceptional else report to user 

上述(儘管不是合理的正確)是否是一個很好的方法來做到這一點?

+0

如果用戶刪除'if'和'using'之間的文件,該怎麼辦? – SLaks 2012-02-29 17:36:46

+1

職位:http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx – cadrell0 2012-02-29 17:40:31

回答

3

首先你可以驗證,如果你有機會獲得該文件,之後,如果該文件存在之間的流創建使用try catch塊,看:

public bool HasDirectoryAccess(FileSystemRights fileSystemRights, string directoryPath) 
{ 
    DirectorySecurity directorySecurity = Directory.GetAccessControl(directoryPath); 

    foreach (FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) 
    { 
     if ((rule.FileSystemRights & fileSystemRights) != 0) 
     { 
      return true; 
     } 
    } 

    return false; 
} 

所以:

if (this.HasDirectoryAccess(FileSystemRights.Read, path) 
{ 
    if (File.Exists(path)) 
    { 
     try 
     {  
      using (Streamwriter ....)  
      { 
       // write code 
      } 
     } 
     catch (Exception ex)    
     {  
      // throw error if exceptional else report to user or treat it       
     } 
    }  
    else 
    { 
     // throw error if exceptional else report to user 
    } 
} 

或者你可以使用try catch來驗證所有東西,並在try catch內創建流。

4

訪問外部資源總是容易出錯。使用try catch塊來管理訪問文件系統並管理異常處理(路徑/文件存在,文件訪問權限等)

1

您可以使用類似這樣

private bool CanAccessFile(string FileName) 
    { 
     try 
     { 
      var fileToRead = new FileInfo(FileName); 
      FileStream f = fileToRead.Open(FileMode.Open, FileAccess.Read, FileShare.None); 
      /* 
       * Since the file is opened now close it and we can access it 
       */ 
      f.Close(); 
      return true; 
     } 
     catch (Exception ex) 
     { 
      Debug.WriteLine("Cannot open " + FileName + " for reading. Exception raised - " + ex.Message); 
     } 

     return false; 
    } 
+0

+0 - 雖然有可能做到並有一些好處,但仍需要精確處理在實際使用文件作爲文件屬性時相同的條件可以在檢查權限和實際訪問之間改變。在實際使用中處理錯誤更可靠。 – 2012-02-29 17:46:59