我经常发现自己以某种方式与文件进行交互,但是在编写代码之后,我总是不确定它实际上是多么生硬。问题是我不完全确定与文件相关的操作是如何失败的,因此,这是处理期望的最佳方法。
简单的解决方案似乎只是捕获代码抛出的任何 IOExceptions 并向用户提供“无法访问的文件”错误消息,但是否有可能获得更细粒度的错误消息。有没有办法确定文件被另一个程序锁定等错误与由于硬件错误导致数据不可读之间的区别?
鉴于以下 C# 代码,您将如何以用户友好(尽可能提供信息)的方式处理错误?
public class IO
{
public List<string> ReadFile(string path)
{
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
throw new FileNotFoundException();
}
StreamReader reader = file.OpenText();
List<string> text = new List<string>();
while (!reader.EndOfStream)
{
text.Add(reader.ReadLine());
}
reader.Close();
reader.Dispose();
return text;
}
public void WriteFile(List<string> text, string path)
{
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
throw new FileNotFoundException();
}
StreamWriter writer = file.CreateText();
foreach(string line in text)
{
writer.WriteLine(line);
}
writer.Flush();
writer.Close();
writer.Dispose();
}
}