打开文件时处理错误的最佳方法

处理文件(打开)是一种特别容易出错的活动。

如果您要编写一个函数来执行此操作(尽管是微不足道的),那么在处理错误的wrt中编写它的最佳方法是什么?

以下是好的吗?

if (File.Exists(path)) { using (Streamwriter ....) { // write code } } else // throw error if exceptional else report to user 

上述(虽然不是语法正确)是一个很好的方法吗?

首先,您可以validation您是否有权访问该文件,之后,如果该文件存在,并且在创建流之间使用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 catchvalidation所有内容,并在try catch中创建流。

访问外部资源总是容易出错。 使用try catch块来管理对文件系统的访问并管理exception处理(路径/文件存在,文件访问权限等)

你可以使用这样的东西

  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; }