Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does StreamWriter overwrite my file?

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();
    }
}
like image 960
Bxcb Sbdsb Avatar asked Oct 25 '12 09:10

Bxcb Sbdsb


People also ask

Does StreamWriter overwrite file?

StreamWriter(String, Boolean) Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Does FileMode create overwrite?

FileMode parameters control whether a file is overwritten, created, opened, or some combination thereof. Use Open to open an existing file. To append to a file, use Append . To truncate a file or create a file if it doesn't exist, use Create .

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.

Do I need to close StreamWriter?

You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions.


1 Answers

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);
like image 75
Alvin Wong Avatar answered Sep 30 '22 06:09

Alvin Wong