追赶太阳的人 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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效