通过C#在位编辑一个文本文件 [英] Editing a text file in place through C#

查看:130
本文介绍了通过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).

推荐答案

由于文件是如此之大,你可能想看看的的内存映射文件。基本上你需要将文件/流指针移动到的位置的文件中,覆盖该位置,然后将文件刷新到磁盘。你不会需要加载整个文件到内存中。

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.

例如,不使用内存映射文件,下面覆盖的ASCII文件的一部分。 ARG游戏输入文件,基于零开始索引和新的文本。

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.

    static void Main(string[] args)
    {
        string inputFilename = args[0];
        int startIndex = int.Parse(args[1]);
        string newText = args[2];

        using (FileStream fs = new FileStream(inputFilename, FileMode.Open, FileAccess.Write))
        {
            fs.Position = startIndex;
            byte[] newTextBytes = Encoding.ASCII.GetBytes(newText);
            fs.Write(newTextBytes, 0, newTextBytes.Length);
        }
    }

这篇关于通过C#在位编辑一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆