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

I am trying to write to a file using FileStream and want to write a second line and then write the first line. I use Seek () to go back to the top 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 can I not 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); 

The following is written to the file:

 first string hould be in the end 

I want him to be

 first string string that should be in the end 

thanks

+4
source share
3 answers

First you need to search in a file equal to the length of the first line.

 fs.Seek(stringToWrite2.Length, SeekOrigin.Begin); fs.Write(stringToWrite, 0, stringToWrite.Length); fs.Seek(0, SeekOrigin.Begin); 

Also, be sure to delete your stream ( using ).

+4
source

You cannot insert into a file and push back existing content. You can only overwrite or expand.

Therefore, you cannot write part of a file until you know the contents of everything that precedes it.

+3
source

Depending on what you are trying to achieve, you may need to write two different files, one of which is a temporary file.

  • Create a temporary file with "second" content
  • Create a new file with the "first" content
  • Open the first file, read its contents and add the second file

If this is a recurring requirement in a larger solution, maybe what you want is some kind of database? Perhaps a file database like SqlLite or BerkeleyDb .

A similar problem is discussed here .

+2
source

All Articles