Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top