簡體   English   中英

File.WriteAllText是否真的拋出FileNotFoundException?

[英]Does File.WriteAllText really throws a 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>標簽?

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,除了包含較少的健全性檢查(這意味着它基本上直接轉換為上面的代碼)之外,其他情況相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM