0

Can you please help me here... I wants to create a text file through application (c#-.Net2005)and need to update it for every sucessful transaction...I created text file and also updation is sucessful but new line is gets added as last line...BUT I want newly added line should be a TOPMOST line in the text file...Can you please tell me how can I do this in c#.

Avinash
  • 371
  • 1
  • 5
  • 14
  • 2
    It's going to be a costly operation, requiring a complete rewrite of the file for every insertion. Are you sure you can't live with the more standard behaviour of adding to the bottom of the file? – spender Oct 27 '10 at 11:57

2 Answers2

2
string topLine = "....";
System.IO.File.WriteAllText("filename.blah",
                              topLine + System.Environment.NewLine + 
                                   System.IO.File.ReadAllText("filename.blah") );

Personally I think this requirement should be questioned.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
2

If it is on line you update and only one line leave space at the beginning of the file and write to this position using

FileStream.write( buffer, 0, space_reserved_for_line);
//be aware that this will overwrite what has been written there

If you want to keep some kind of a log file, write the line to a new file and appen the rest of the other file. This is very expensive (performancewise). Unless you have very good reasons, you most probably do not want to do this.

There is no acceptable way to write a log-file where the top-most entry ist the most recent one.

hth

Mario

Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36
  • Thanks guies..for your update... Now I planned not to write a new line as a topmost line as I am already imporing few files of 30-40 MB into database...it will kill application performanance...thx – Avinash Oct 27 '10 at 12:16