StreamWriter doesn't write to a file that doesn't exist

annonymously picture annonymously · Jan 7, 2012 · Viewed 20.1k times · Source

I am making a level editor for my game, and most of it is working except... When I try to save my file (XML) the file doesn't get created, and in the output box I get:

A first chance exception of type 'System.NullReferenceException'

The funny thing is that it only happens if the file doesn't exist, but it works correctly if I overwrite another file.

here is the code I'm using:

using (StreamWriter stream = new StreamWriter(filePath))
{
    stream.Write(data);
    stream.Close();
}

data is a string (this is not the problem because it works when I overwrite the file)

Answer

Grant Thomas picture Grant Thomas · Jan 8, 2012

You're missing a constructor which takes a boolean that can aid in creating the file:

using (StreamWriter stream = new StreamWriter(filePath, false)) {
    stream.Write(data);
    stream.Close();
}

The logic is actually is little more complex than that, however:

public StreamWriter( string path, bool append )

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.