Oztaco
Oztaco

Reputation: 3459

C# add text to text file without rewriting it?

Let's say I have the following code:

StreamWriter sw = new StreamWriter(File.OpenWrite(Path));
sw.Write("Some stuff here");
sw.Dispose();

This code replaces the contents of the file with "Some stuff here," however I would like to add text to the file rather than replacing the text. How would I do this?

Upvotes: 6

Views: 19616

Answers (6)

Alex
Alex

Reputation: 35409

Use the append parameter:

StreamWriter sw = new StreamWriter(Path, true);

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

To append text to a file, you can open it using FileMode.Append.

StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));

This is just one way to do it. Although, if you don't explicitly need the StreamWriter object, I would recommend using what others have suggested: File.AppendAllText.

Upvotes: 0

rcravens
rcravens

Reputation: 8390

Check out System.IO.File.AppendAllText

http://msdn.microsoft.com/en-us/library/ms143356.aspx

You can do what you want doing something like

File.AppendAllText(path, text);

Upvotes: 4

Joe
Joe

Reputation: 42627

There is a StreamWriter constructor which takes a bool as the 2nd parameter, which instructs the writer to append if true.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could use the File.AppendAllText method and replace the 3 lines of code you have with:

File.AppendAllText(Path, "blah");

This way you don't have to worry about streams and disposing them (even in the event of an exception which by the way you are not doing properly) and the code is pretty simple and straightforward to the point.

Upvotes: 8

zmbq
zmbq

Reputation: 39013

You need to tell the StreamWriter you want to append:

var sw = new StreamWriter(path, true);

File.OpenWrite doesn't support appending.

Upvotes: 5

Related Questions