4

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

Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • When you seek to the start of the stream you are setting the position you will write to. If there is data already there it will be overwritten. – Russell Troywest Apr 17 '11 at 10:12

3 Answers3

4

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

Talljoe
  • 14,593
  • 4
  • 43
  • 39
  • But the reason why I am writing so is because I do not know first string ( and hence the length ) when I am writing the second string – manojlds Apr 17 '11 at 10:15
  • In that case you'll have to re-read what you already wrote, write it again further into the file, then write the string that goes in the front. – Talljoe Apr 17 '11 at 10:29
  • That makes sense. Accepting as answer. – manojlds Apr 17 '11 at 10:30
3

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

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

  1. Create a temporary file with "second" content
  2. Create a new file with the "first" content
  3. Open the first file, read its content and append to the second file

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

A similar problem is discussed here.

Community
  • 1
  • 1
Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61