0

So this is just a thought... Say I wanted to insert a line into a file at the first linebreak, but I didn't want to read the entire file into memory. Is there a way to just read the file into memory line by line and then, when the first linebreak is reached, insert a line and close the file reader?

Thank you!

Sorry for the earlier typo in my title/description

gfppaste
  • 1,111
  • 4
  • 18
  • 48

2 Answers2

2

you can read one byte at a time and intercept the line break character. Then at that position do a stream.WriteLine(). You'll hve to open file for read+write

Edit: I thought of using the FileStream object, but I'm not sure. Any for now try the suggestion mentioned here: http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/e5077949-5d23-4d26-a530-6d503745a197

Edit again: check How to both read and write a file in C#

Community
  • 1
  • 1
deostroll
  • 11,661
  • 21
  • 90
  • 161
0

Try the following:

using (StreamWriter w = File.AppendText("test.txt"))
{
     w.Write("\r\nTest");
     w.Flush();
     w.Close();
}

Update:

For inserting the line in existing text file (I assume you're working with text files since you mentioned line break): there isn't a way to do it with file I/O API - you must read the text after the first line break, overwrite the file and add original trailing text.

BluesRockAddict
  • 15,525
  • 3
  • 37
  • 35