2012-02-18 22 views
1

文件说:File.WriteAllText是否真的会引发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,并在例外它列出:

// System.IO.FileNotFoundException: 
//  The file specified in path was not found. 

在这种情况下,会出现这种情况?如果它总是创建一个文件,那么它不应该抛出FileNotFoundException ...

文档是否错误?或者它可能丢失了<remarks>标签?

+0

如果找不到路径的一部分,该怎么办?那会是'FileNotFoundException'或'DirectoryNotFound'吗? – 2012-02-18 04:23:25

+0

@JohnSaunders是一个'DirectoryNotFoundException':'{“找不到路径'C:\\ ZZZZZZ \\ ZZZ \\ TEST.txt'的一部分。”}' – BrunoLM 2012-02-18 04:25:25

+2

这是一个复制粘贴File.ReadAllText()文章。 – 2012-02-18 09:19:09

回答

5

File.WriteAllText最终调用:

private static void InternalWriteAllText(string path, string contents, Encoding encoding) 
{ 
    using (StreamWriter streamWriter = new StreamWriter(path, false, encoding)) 
    { 
     streamWriter.Write(contents); 
    } 
} 

所有(因为FileStream可以抛出除外)之前调用InternalWriteAllTextArgumentExceptionArgumentNullException但理论上抛出的异常的streamWriter.Write(contents);可能会抛出异常。尽管基于它的作用以及streamWriter是如何打开的,但不太可能。

我不一定会说这个文档是错误本身,更重要的是MS通过记录(非常罕见)的可能性覆盖了他们的屁股。

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

UPDATE

刚才检查mscorlib V2.0.0.0,相同的情况下,除了它包含较少的健全性检查(这意味着它基本上直接转化为上面的代码)。

相关问题