文档说:
// Summary:
// Creates a new file, writes the specified string to the file, and then closes
// the file. If the target file already exists, it is overwritten.
第一行第一句:Creates a new file
,并列出了异常(exception)情况:
// System.IO.FileNotFoundException:
// The file specified in path was not found.
什么情况下会发生这种情况?如果它总是创建一个文件,那么它不应该抛出 FileNotFoundException...
文档有误吗?或者是否缺少 <remarks>
也许是标签?
最佳答案
File.WriteAllText
最终调用:
private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter streamWriter = new StreamWriter(path, false, encoding))
{
streamWriter.Write(contents);
}
}
在调用 InternalWriteAllText
之前抛出的所有异常都会抛出 ArgumentException
或 ArgumentNullException
但理论上(因为 FileStream
> 可能会引发异常)streamWriter.Write(contents);
可能会引发异常。但根据它的作用以及 streamWriter
的打开方式,可能性很小。
我不一定会说该文档本身就是错误,更多的是微软通过记录(非常罕见的)可能性来掩盖他们的屁股。
来源:使用 ILSpy 反编译 mscorlib
v4.0.0.0。
更新
刚刚检查了 mscorlib
v2.0.0.0,情况相同,只是它包含较少的健全性检查(意味着它基本上直接转换为上面的代码)。
关于c# - File.WriteAllText 真的会抛出 FileNotFoundException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9338512/