BananaVenom
BananaVenom

Reputation: 78

Adding to text file without deleting

I need to add 4 variable numbers into a single line but using the current code it just replaces the numbers thus making it pointless.

using (StreamWriter writer = new StreamWriter("build.txt"))
{
    writer.Write(" " + layer + " " + x + " " + y + " " + block);
    Console.WriteLine("[" + layer + "," + x + "," + y + "," + block + "]");                   
}

so I needed it to write...

 l x y b l x y b l x y b l x y b ...

...but it did not work out like that, and the internet wasn't particularly helpful, hopefully here can help.

Upvotes: 2

Views: 6812

Answers (3)

Mike Christensen
Mike Christensen

Reputation: 91716

You should use File.AppendText for this:

using (StreamWriter sw = File.AppendText("build.txt")) 
{
   sw.Write(" " + layer + " " + x + " " + y + " " + block);
   Console.WriteLine("[" + layer + "," + x + "," + y + "," + block + "]");
}

Upvotes: 2

Steve
Steve

Reputation: 216352

StreamWriter has a constructor that accepts a boolean value to indicate that you want to append to the current text and not overwrite it

using (StreamWriter writer = new StreamWriter("build.txt", true))
{
    .....
}

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1503489

I would use File.AppendAllText, personally... That way you can just specify the text you want to write, and the method will open the file, append the text, and then close the file.

If you really want to use the writer though, you could use File.AppendText:

using (var writer = File.AppendText("build.txt"))
{
    writer.Write(...);
}

Or you can use the StreamWriter constructor with an append parameter. I'd definitely recommend using the methods in File though - they're much clearer to read.

Upvotes: 9

Related Questions