Avinash
Avinash

Reputation: 391

How to append line at the Top of exising text file in c#

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

Upvotes: 1

Views: 4451

Answers (2)

Mario The Spoon
Mario The Spoon

Reputation: 4859

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

Upvotes: 2

Preet Sangha
Preet Sangha

Reputation: 65516

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.

Upvotes: 2

Related Questions