Question

Documentation says:

// 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.

First line, first sentence: Creates a new file, and on the exceptions it lists:

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

In which case would this happen? If it always create a file then it shouldn't thrown a FileNotFoundException...

Is the documentation wrong? Or is it missing a <remarks> tag perhaps?

Was it helpful?

Solution

File.WriteAllText eventually calls:

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

All of the exceptions thrown prior to the call to InternalWriteAllText throw ArgumentException or ArgumentNullException but theoretically (since FileStream can throw the exception) the streamWriter.Write(contents); could potentially throw the exception. Very unlikely though based on what it does and how the streamWriter is opened.

I wouldn't necessarily say the doc is wrong per se, more that MS is covering their butt by documenting the (very rare) possibility.

Source: Decompiling mscorlib v4.0.0.0 using ILSpy.

UPDATE

Just checked mscorlib v2.0.0.0, same case except it contains fewer sanity checks (meaning it basically translates directly to the code above).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top