通过 C# 就地编辑文本文件
我有一个巨大的文本文件,大小> 4GB,我想以编程方式替换其中的一些文本。我知道必须替换文本的行号,但问题是我不想将所有文本(以及替换的行)复制到第二个文件。我必须在源文件中执行此操作。有没有办法在 C# 中做到这一点?
必须替换的文本与源文本的大小完全相同(如果这有帮助)。
I have a huge text file, size > 4GB and I want to replace some text in it programmatically. I know the line number at which I have to replace the text but the problem is that I do not want to copy all the text (along with my replaced line) to a second file. I have to do this within the source file. Is there a way to do this in C#?
The text which has to be replaced is exactly the same size as the source text (if this helps).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于文件太大,您可能需要查看 .NET 4.0 对 内存映射文件。基本上,您需要将文件/流指针移动到文件中的位置,覆盖该位置,然后将文件刷新到磁盘。您不需要将整个文件加载到内存中。
例如,在不使用内存映射文件的情况下,以下内容将覆盖 ascii 文件的一部分。 Args 是输入文件、从零开始的起始索引和新文本。
Since the file is so large you may want to take a look at the .NET 4.0 support for memory mapped files. Basically you'll need to move the file/stream pointer to the location in the file, overwrite that location, then flush the file to disk. You won't need to load the entire file into memory.
For example, without using memory mapped files, the following will overwrite a part of an ascii file. Args are the input file, the zero based start index and the new text.
除非新文本与旧文本的大小完全相同,否则您将必须重新写入文件。没有办法解决这个问题。您至少可以在不将整个文件保留在内存中的情况下执行此操作。
Unless the new text is exactly the same size as the old text, you will have to re-write the file. There is no way around it. You can at least do this without keeping the entire file in memory.
您好,我测试了以下内容 - 效果很好。这迎合了由 Environment.NewLine 分隔的可变长度行。如果您有固定长度的行,您可以直接查找它。要将字节转换为字符串,反之亦然,您可以使用编码。
Hello I tested the following -works well.This caters to variable length lines separated by Environment.NewLine. if you have fixed length lines you can straightaway seek to it.For converting bytes to string and vice versa you can use Encoding.
我猜您会想要使用 FileStream 类并寻找您的位置,并放置更新的数据。
I'm guessing you'll want to use the FileStream class and seek to your positon, and place your updated data.