0

How to add a line to already existing file with StreamWriter? I Tried doing researches but nothing fits my needs.

I have this:

using (StreamWriter writer = new StreamWriter(appdata + @"\FILE.txt"))
{ 
   writer.WriteLine(Environment.NewLine + "newline"); 
}

And instead of replacing the text that is in the file I want to add a new line to it. Also, if the file doesn't exist, it should create itself. This code does in fact what I described, but it replaces (so for example if you click once it's newline and then again it's just newline2. newline is not there. It should look like:

newline <

        I want this effect

newline2<

and then add more after a new line.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
NorteX
  • 45
  • 1
  • 3
  • 7
  • for just adding lines, I recommend `File.AppendAllLines` https://stackoverflow.com/questions/15379136/append-to-a-text-file-using-writealllines – Slai Dec 23 '18 at 13:22
  • I found the duplicate by Googling "c# append to text file", you should spend some more time searching before asking questions – Camilo Terevinto Dec 23 '18 at 13:34

2 Answers2

1

Use the constructor taking an additional bool append parameter:

using (StreamWriter writer = new StreamWriter(appdata + @"\FILE.txt", true )) { 
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
0

There is a flag in the constructor overload to advocate the writer to append the new content at end of file. You can pass true as argument to append new content instead of replacing whole content:

new StreamWriter(appdata + @"\FILE.txt", append: true);
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • I added "true" and it's still removing content of the file replacing it with new – NorteX Dec 23 '18 at 13:07
  • that shouldn't be the case, are you sure? – Ehsan Sajjad Dec 23 '18 at 13:09
  • my exact code using (StreamWriter writer = new StreamWriter(appdata + @"\important.txt")) { writer.WriteLine(Environment.NewLine + generatedCode.Text, true); } the generatedCode Text is changed every click and the file updates with the click too (after the text change) and it doesnt work.. still – NorteX Dec 23 '18 at 13:11
  • 1
    That's not what Ehsan and me were proposing. You have to add the true to the SteramWriter constructor, not the WriteLine call. – Klaus Gütter Dec 23 '18 at 13:13
  • @NorteX please see the code snippet posted carefully :) – Ehsan Sajjad Dec 23 '18 at 13:15
  • Okay, it works now, sorry for being incautious... – NorteX Dec 23 '18 at 13:21