Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Random write to file - writing the second line before the first line

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

like image 238
manojlds Avatar asked Jan 19 '23 23:01

manojlds


2 Answers

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).

like image 90
Talljoe Avatar answered Jan 22 '23 14:01

Talljoe


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.

like image 33
David Heffernan Avatar answered Jan 22 '23 13:01

David Heffernan