c# - File.WriteAllText 真的会抛出 FileNotFoundException 吗?

标签 c# file filenotfoundexception

文档说:

// 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 之前抛出的所有异常都会抛出 ArgumentExceptionArgumentNullException 但理论上(因为 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/

相关文章:

c# - WebClient.DownloadData 挂起

c# - NumLock isKeyLocked 不起作用

c# - 是否可以在 Lambda 表达式中包含 SqlFunctions.StringConvert?

image - Symfony 1.4 sfWidgetFormInputFileEditable 自定义

python - 从 python 中的另一个文件导入类 - 我知道修复方法,但为什么原始文件不起作用?

java - 如何使用 Tomcat 打开 Java Spring 项目中的文件

java - 从存储导入文件时出现 FileNotFoundException (Android Studio)

c# - 从文本文件中删除重复行?

c - 使用 fscanf() 读取一行时遇到问题

java - addProvider bouncycaSTLe 文件未找到异常