我正在尝试使用FileStream写入文件,并希望先写第二行,然后再写第一行。我使用Seek()在写完第二行后返回文件开头,并写入第一行。但它会替换第二行(或部分替换,具体取决于第一行的长度)。如何避免替换第二行?
var fs = new FileStream("my.txt", FileMode.Create);
byte[] stringToWrite = Encoding.UTF8.GetBytes("string that should be in the end");
byte[] stringToWrite2 = Encoding.UTF8.GetBytes("first string\n");
fs.Write(stringToWrite, 0, stringToWrite.Length);
fs.Seek(0, SeekOrigin.Begin);
fs.Write(stringToWrite2, 0, stringToWrite2.Length);
以下内容已写入文件:
first string
hould be in the end
I want it to be
first string
string that should be in the end
谢谢