C# .NET - how to write at specific position in a text file??

Asked By Sanya on 31-May-11 06:15 AM
i want to create a file like this:
11sdwferdfsvcbxnamsj
11csfdgfhgjhkjlkmvnc
11sddeafsgdhfjgkhljs
12dsfegchdyjfhcndjfk
12asddfghjklmnbvcdfgh
12adsfdgfhgjhkcmvnxb
13adsfdgfhgjcnxmcsvi
13aszxcvdfertgfdvcbx
13sfegdbcnvmfkgjthyu
.
.
.ect
(the line are in a set 1st set is of all 11s then set of all 12s then 13s then 14s etc)
there is one more file which contains same data but its data is not sorted its random like:
12adsfdgfhgjhkcmvnxb
11csfdgfhgjhkjlkmvnc
13aszxcvdfertgfdvcbx
12asddfghjklmnbvcdfgh
.
.
.
.etc
i want to read last line from the above file and write it into my file in its proper set for eg if last line in above file  is 12asfdgetrywhsgdtehf then it should write in my file at a next line to 12adsfdgfhgjhkcmvnxb
my file should becom like this:
11sdwferdfsvcbxnamsj
11csfdgfhgjhkjlkmvnc
11sddeafsgdhfjgkhljs
12dsfegchdyjfhcndjfk
12asddfghjklmnbvcdfgh
12adsfdgfhgjhkcmvnxb
12asfdgetrywhsgdtehf
13adsfdgfhgjcnxmcsvi
13aszxcvdfertgfdvcbx
13sfegdbcnvmfkgjthyu
.
.
.
etc

i,l read a lastline from unsorted file and write it at specific position  in my sorted file  
 i m able to do reading and matching part but not able to write at specific position:
my code is:
FileStream fs = new FileStream (@"C:\New Folder\sequence.txt",FileMode.Open   , FileAccess.ReadWrite  );
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);
string line;
          while ((line = sr.ReadLine()) != null)
          {
              if (line.Substring(0, 2) == "11")
              {
//here as soon as it matches with 11 it should write text box's value on a line below this line
               sw.WriteLine(textBox1.Text);  // this is not proper coz its writing at the end of file what                                                                                               should i write here plz help me with this part
                  break;
              }

pete rainbow replied to Sanya on 12-Jun-11 08:59 PM
not all streams support this sort of readwrite ie fully random access

i'd go for the solution of reading from one file and writing into a new temp file as you go

and then overwriting orig file with new file

this also has the advantage of potentially being more exception safe in that you won't end up with the orig file currupted when the code goes wrong...