MCloud
MCloud

Reputation: 3

Why can I not append a line to a file using StreamWriter?

Why does my program overwrite the same line in the file?

I want it to record a line every time I use the StreamWriter.

String path = @"c:\Observer\Employer\Employer.txt";
TextWriter write1 = new StreamWriter(path);

if (!File.Exists(path))
{
    File.Create(path);
    TextWriter write2 = new StreamWriter(path);
    write2.WriteLine(Info);
    write2.Close();
}
else if (File.Exists(path))
{
    write1.WriteLine(Info);
    write1.Close();
}

write1.Close();

Upvotes: 0

Views: 60

Answers (3)

Thoth2020
Thoth2020

Reputation: 35

You need open the file in append mode in order to add lines to it. Use the optional second parameter set to true, like so:

TextWriter write1 = new StreamWriter(path, true);

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66509

By default, the overload you're using overwrites the file. Here's what it looks like under the covers:

public StreamWriter(String path) 
    : this(path, false, UTF8NoBOM, DefaultBufferSize) {
}

The second parameter tells it whether to append (true) or overwrite (false).

You have to explicitly tell it to append text to the file:

TextWriter write1 = new StreamWriter(path, true);

Upvotes: 5

AlexD
AlexD

Reputation: 32596

As @GrantWinney wrote, this is expected behavior. Anyway, instead of the entire code, you may want to use just

File.AppendAllText(path, Info)

instead. It seems it has all the functionality you need. See http://msdn.microsoft.com/en-us/library/ms143356.aspx

Upvotes: 3

Related Questions