FileStream Append Data at the top

后端 未结 3 1266
南笙
南笙 2021-01-23 09:10

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 :

相关标签:
3条回答
  • 2021-01-23 09:45

    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.

    0 讨论(0)
  • 2021-01-23 09:58

    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.

    0 讨论(0)
  • 2021-01-23 10:00

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

    0 讨论(0)
提交回复
热议问题