Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing a text file in place through C#

Tags:

c#

text-files

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

like image 490
Aamir Avatar asked Jun 23 '10 18:06

Aamir


Video Answer


2 Answers

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.

    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);
        }
    }
like image 114
Shea Avatar answered Oct 21 '22 09:10

Shea


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.

like image 31
Joel Coehoorn Avatar answered Oct 21 '22 07:10

Joel Coehoorn