Mor*_*sen 16 .net c# file-io exception-handling
我常常发现自己以某种方式与文件进行交互,但在编写代码后,我总是不确定它实际上是多么糟糕.问题是我不完全确定文件相关操作如何失败,因此是处理预期的最佳方法.
简单的解决方案似乎只是捕获代码抛出的任何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();
}
}
Run Code Online (Sandbox Code Playgroud)
Dus*_*man 13
...但是有可能获得更细粒度的错误消息.
是.继续捕获IOException,并使用该Exception.ToString()方法来显示相对相关的错误消息.请注意,.NET Framework生成的异常将提供这些有用的字符串,但是如果要抛出自己的异常,则必须记住将该字符串插入到Exception构造函数中,如:
throw new FileNotFoundException("File not found");
另外,根据Scott Dorman,绝对使用该using声明.但要注意的是,using声明实际上并不是catch什么,这应该是它应该的方式.例如,您测试文件是否存在将导致竞争条件可能相当令人烦恼.把它放在那里对你没有任何好处.那么,现在,对于读者我们有:
try {
using (StreamReader reader = file.OpenText()) {
// Your processing code here
}
} catch (IOException e) {
UI.AlertUserSomehow(e.ToString());
}Run Code Online (Sandbox Code Playgroud)
总之,对于基本的文件操作:
1.使用using
2,敷用语句或函数在try/ catch那catch上课IOException
3.使用Exception.ToString()在你catch得到一个有用的错误消息
4.不要尝试自行检测例外文件的问题.让.NET为你做投掷.
您应该更改的第一件事是调用StreamWriter和StreamReader将它们包装在using语句中,如下所示:
using (StreamReader reader = file.OpenText())
{
List<string> text = new List<string>();
while (!reader.EndOfStream)
{
text.Add(reader.ReadLine());
}
}
Run Code Online (Sandbox Code Playgroud)
这将负责为您调用Close和Dispose,并实际将其包装在try/finally块中,以便实际编译的代码如下所示:
StreamReader reader = file.OpenText();
try
{
List<string> text = new List<string>();
while (!reader.EndOfStream)
{
text.Add(reader.ReadLine());
}
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,即使发生异常,也可以确保流关闭.
至于任何更明确的异常处理,它实际上取决于你想要发生什么.在您的示例中,您显式测试文件是否存在并抛出FileNotFoundException,这可能对您的用户来说已经足够,但可能没有.