如何阅读大(1 GB)的txt在.NET文件? [英] How to read a large (1 GB) txt file in .NET?

查看:175
本文介绍了如何阅读大(1 GB)的txt在.NET文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要按行读入行1 GB的文本文件。什么是做到这一点的最好和最快的方式?

 私人无效ReadTxtFile()
{
    字符串文件路径=的String.Empty;
    文件路径= openFileDialog1.FileName;
    如果(string.IsNullOrEmpty(文件路径))
    {
        使用(StreamReader的SR =新的StreamReader(文件路径))
        {
            串线;
            而((行= sr.ReadLine())!= NULL)
            {
                FormatData将(线);
            }
        }
    }
}

FormatData将()我检查线路的起始字,必须用一个词匹配和基于增量的整型变量。

 无效FormatData将(串线)
{
    如果(line.StartWith(字))
    {
        globalIntVariable ++;
    }
}


解决方案

如果您使用的是.NET 4.0,尝试<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.aspx\">MemoryMappedFile这是一款专类此方案。

您可以使用 StreamReader.ReadLine 其他。

I have a 1 GB text file which I need to read line by line. What is the best and fastest way to do this?

private void ReadTxtFile()
{            
    string filePath = string.Empty;
    filePath = openFileDialog1.FileName;
    if (string.IsNullOrEmpty(filePath))
    {
        using (StreamReader sr = new StreamReader(filePath))
        {
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                FormatData(line);                        
            }
        }
    }
}

In FormatData() I check the starting word of line which must be matched with a word and based on that increment an integer variable.

void FormatData(string line)
{
    if (line.StartWith(word))
    {
        globalIntVariable++;
    }
}

解决方案

If you are using .NET 4.0, try MemoryMappedFile which is a designed class for this scenario.

You can use StreamReader.ReadLine otherwise.

这篇关于如何阅读大(1 GB)的txt在.NET文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆