2012-02-29 76 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