gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:56 24 4
gpt4 key购买 nike

文档说:

// 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 的打开方式,这种可能性很小。

我不一定会说该文档本身错误,更多的是 MS 通过记录(非常罕见的)可能性来掩盖他们的屁股。

来源:使用 ILSpy 反编译 mscorlib v4.0.0.0。

更新

刚刚检查了 mscorlib v2.0.0.0,同样的情况,只是它包含更少的完整性检查(意味着它基本上直接转换为上面的代码)。

关于c# - File.WriteAllText 真的会抛出 FileNotFoundException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9338512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com