追赶太阳的人 2022-02-26 21:13 采纳率: 100%
浏览 40
已结题

c#读写大文件(大于20g)

c#读写大文件(大于20g),是二进制大文件的读写,谢谢各位

  • 写回答

4条回答 默认 最新

  • CSDN专家-showbo 2022-02-26 21:31
    关注

    The problem with your solution is that you recreate the streams in each iteration. Try this version:

    
    const int MAX_BUFFER = 33554432; //32MB
    byte[] buffer = new byte[MAX_BUFFER];
    int bytesRead;
    StringBuilder currentLine = new StringBuilder();
    
    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
    using (BufferedStream bs = new BufferedStream(fs))
    {
        string line;
        bool stop = false;
        var memoryStream = new MemoryStream(buffer);
        var stream = new StreamReader(memoryStream);
        while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0)
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
    
            while (!stream.EndOfStream)
            {
                line = ReadLineWithAccumulation(stream, currentLine);
    
                if (line != null)
                {
                    //process line
                }
            }
        }
    }
    
    private string ReadLineWithAccumulation(StreamReader stream, StringBuilder currentLine)
    {
        while (stream.Read(buffer, 0, 1) > 0)
        {
            if (charBuffer [0].Equals('\n'))
            {
                string result = currentLine.ToString();
                currentLine.Clear();
    
                if (result.Last() == '\r') //remove if newlines are single character
                {
                    result = result.Substring(0, result.Length - 1);
                }
    
                return result;
            }
            else
            {
                currentLine.Append(charBuffer [0]);
            }
        }
    
        return null;  //line not complete yet
    }
    
    private char[] charBuffer = new char[1];
    


    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 3月6日
  • 已采纳回答 2月26日
  • 创建了问题 2月26日

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法