C# - 随机写入文件 - 在第一行之前写入第二行
我正在尝试使用 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
我希望它是
first string
string that should be in the end
谢谢
I am trying to write to a file using a FileStream and want to write the second line and then write the first line. I use Seek() to go back to the beginning after writing the second line and then write the first line. It replaces the second line ( or part of it depending on the length of the first line.) How do I not make it replace the second line?
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);
Following is written to the file:
first string
hould be in the end
I want it to be
first string
string that should be in the end
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您首先需要在文件中查找等于第一个字符串的长度。
另外,不要忘记处置您的流(
using
)。You first need to seek into the file equal to the length of the first string.
Also, don't forget to dispose of your stream (
using
).您无法插入文件并将现有内容推回。您只能覆盖或扩展。
因此,在您知道文件前面所有内容的内容之前,您无法写入该文件的一部分。
You can't insert into a file and push the existing contents back. You can only overwrite or extend.
You therefore can't write a piece of the file until you know the contents of all that precedes it.
根据您想要实现的目标,您可能需要写入两个不同的文件,其中一个是临时文件。
如果这是更大的解决方案中反复出现的要求,也许您想要的是某种数据库的?也许是基于文件的数据库,例如 SqlLite 或 BerkeleyDb。
此处讨论了类似的问题。
Depending on what you are trying to achieve, you may need to write to two different files, one being a temporary file.
If this a recurring requirement in a bigger solution, maybe what you want is some kind of database? Maybe a file-based database like SqlLite or BerkeleyDb.
A similar problem is discussed here.