I am trying to write to a file using a FileStream and want to write the second line and then write the first line. I use Seek() to go back to the beginning after writing the second line and then write the first line. It replaces the second line ( or part of it depending on the length of the first line.) How do I not make it replace the second line?
var fs = new FileStream("my.txt", FileMode.Create);
byte[] stringToWrite = Encoding.UTF8.GetBytes("string that should be in the end");
byte[] stringToWrite2 = Encoding.UTF8.GetBytes("first string\n");
fs.Write(stringToWrite, 0, stringToWrite.Length);
fs.Seek(0, SeekOrigin.Begin);
fs.Write(stringToWrite2, 0, stringToWrite2.Length);
Following is written to the file:
first string
hould be in the end
I want it to be
first string
string that should be in the end
Thanks
You first need to seek into the file equal to the length of the first string.
fs.Seek(stringToWrite2.Length, SeekOrigin.Begin);
fs.Write(stringToWrite, 0, stringToWrite.Length);
fs.Seek(0, SeekOrigin.Begin);
Also, don't forget to dispose of your stream (using
).
You can't insert into a file and push the existing contents back. You can only overwrite or extend.
You therefore can't write a piece of the file until you know the contents of all that precedes it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With