Why does StreamWriter overwrite my file?

Bxcb Sbdsb picture Bxcb Sbdsb · Oct 25, 2012 · Viewed 19.1k times · Source

I'm using SteamWriter to write something to a text file, however its overwriting the old data with the new data. How can I make sure it will just add the new data instead of overwriting the old data?
my code:

class Program
{
    const string filename = @"C:\log.txt";
    static void Main()
    {
        FileStream fs;
        fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
        StreamWriter writer = new StreamWriter(fs);
        writer.WriteLine("test");

        writer.Close();
        fs.Close();
    }
}

Answer

Alvin Wong picture Alvin Wong · Oct 25, 2012

If you use FileMode.Create, according to MSDN:

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

So you need to use FileMode.Append instead, if you want to add content to the end of the file:

Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);