FileStream Append Data at the top

帅比萌擦擦* 提交于 2019-12-20 04:32:47

问题


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 ?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1062003/filestream-append-data-at-the-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!