Michael Skelton
Michael Skelton

Reputation: 2085

Appending text in C#

When changing the method to AppendText e.g. writeout.AppendText(firstline) I get StreamWriter does not support...

StreamWriter writeout = new StreamWriter(path);
        writeout.WriteLine(firstline);
        writeout.Close();

Instead of overwriting existing data in the text file, I want writeout to append "firstline" to the file

Upvotes: 0

Views: 683

Answers (9)

62071072SP
62071072SP

Reputation: 1935

try
{
    StringBuilder sb = new StringBuilder();
    StreamReader sr = new StreamReader(Path);
    sb.AppendLine(sr.ReadToEnd());
    sb.AppendLine("= = = = = =");
    sb.AppendLine(fileName + " ::::: " + time);
    sr.Dispose();
    if (sw == null)
    {
        sw = new StreamWriter(Path);
    }
    sw.Write(sb.ToString());
    sw.Dispose();

}
catch (Exception e)
{
}

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117084

What about using this?

var lines = new List<string>();
// load lines
System.IO.File.AppendAllLines(path, lines);

Upvotes: 1

Steven Lemmens
Steven Lemmens

Reputation: 1491

You should create your StreamWriter with the explicit option to be able to APPEND to the file. Otherwise, it will always create a new one. Trying to call Append, when the StreamWriter wasn't created to append, gives the error you describe.

I'm not entirely sure, but I think you can do:

StreamWriter writeout = new StreamWriter(path, true);

to give the StreamWriter the ability to append.

Hope this helps.

Upvotes: 4

Scott
Scott

Reputation: 999

Change StreamWriter writeout = new StreamWriter(path); to StreamWriter writeout = new StreamWriter(path, true);.

See http://msdn.microsoft.com/en-us/library/aa328969%28v=vs.71%29.aspx.

Alternatively you can use File.AppendText, e.g. StreamWriter writeout = File.AppendText(path).

Or even just File.AppendAllText, e.g. File.AppendAllText(path, firstline).

Upvotes: 4

Stephan
Stephan

Reputation: 4247

Create the StreamWriter with an additional boolean parameter which specifies whether or not to append to an existing file:

StreamWriter writeout = new StreamWriter(path, true);

Upvotes: 2

mtijn
mtijn

Reputation: 3678

Seek to the end of the stream first by setting StreamWriter.BaseStream.Position to the end of the stream and then continue as normal.

Upvotes: 1

Petar Minchev
Petar Minchev

Reputation: 47373

Use the constructor StreamWriter writeout = new StreamWriter(path, true);

Upvotes: 3

Chuck Norris
Chuck Norris

Reputation: 15190

StreamWriter writeout = new StreamWriter(path,true); //true indicates appending
        writeout.WriteLine(firstline);
        writeout.Close();

Upvotes: 2

Mr47
Mr47

Reputation: 2655

You can use the second parameter of the StreamWriter constructor.
StreamWriter writeout = new StreamWriter(path, true);

Upvotes: 3

Related Questions