Editing a text file in place through C#

后端 未结 4 1919
攒了一身酷
攒了一身酷 2020-12-07 01:10

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 tha

4条回答
  •  渐次进展
    2020-12-07 01:51

    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);
            }
        }
    

提交回复
热议问题