Editing a text file in place through C#

后端 未结 4 1915
攒了一身酷
攒了一身酷 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:42

    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.

     static byte[] ReadNextLine(FileStream fs)
            {
                byte[] nl = new byte[] {(byte) Environment.NewLine[0],(byte) Environment.NewLine[1] };
                List ll = new List();
                bool lineFound = false;
                while (!lineFound)
                {
                    byte b = (byte)fs.ReadByte();
                    if ((int)b == -1) break;
                    ll.Add(b);
                    if (b == nl[0]){
                        b = (byte)fs.ReadByte();
                        ll.Add(b);
                        if (b == nl[1]) lineFound = true;
                    }
                }
              return  ll.Count ==0?null: ll.ToArray();
            }
           static void Main(string[] args)
           {
    
                using (FileStream fs = new FileStream(@"c:\70-528\junk.txt", FileMode.Open, FileAccess.ReadWrite))
                {
                   int replaceLine=1231;
                   byte[] b = null;
                   int lineCount=1;
                   while (lineCount(char)x).ToArray());
                  line = line.Replace("Text1", "Text2");
                    b=line.ToCharArray().Select(x=>(byte)x).ToArray();
                    fs.Write(b, 0, b.Length);
    
                }
    
            }
    

提交回复
热议问题