views:

222

answers:

3

I am working on a utility.

I want to append data at the top of the file, but it is overwritting not appending.

For eg : Consider the file.txt :

Something existing here

Now I want to append "Something more existing here" before the current line. Is there a way I can do without using 2 FileStreams ?

+2  A: 

No. File systems basically don't support inserting data into the file - you either append at the end of the file, or overwrite existing data. At least, I don't know of any file system that does support this, and the standard APIs don't.

To change a file in any other way, the best way is to write a new file, reading from the old file where you need to (in your case after writing the preceding text). Then delete the old file and rename the new file to have the same name as the old file.

(A safer version of this involves renaming the old file, then renaming the new file, then deleting the old file - this allows for recovery if anything goes wrong.)

Jon Skeet
Thanks Jon. Kind of odd though. Thx I will get around using 2 streams then.
cbrcoder
+1  A: 

No. Files do not have an Insert-mode the same way word-processors do.

Sorry, its not what you want to hear, but its a fact.

abelenky
Ah.... I'm basically tied in response time and correctness with Jon Skeet... and I still lose. Behold his greatness.
abelenky
A: 

Yes

FileStream fs = new FileStream( path2, FileMode.OpenOrCreate, FileAccess.ReadWrite );

sw = new StreamWriter( fs );

sw.BaseStream.Seek( 0, 0 );

sw.WriteLine( "write new text" );

sw.close()

This method will overwrite any existing data, akin insert and replace.

bjhamltn