微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在C#中打开一个大文本文件

我有一个包含大约100000篇文章的文本文件.
文件结构是:

.Document ID 42944-YEAR:5
.Date  03\08\11
.Cat  political
Article Content 1

.Document ID 42945-YEAR:5
.Date  03\08\11
.Cat  political
Article Content 2

我想在c#中打开这个文件,逐行处理它.
我试过这段代码

String[] FileLines = File.ReadAllText(
                  TB_SourceFile.Text).Split(Environment.NewLine.tochararray());

但它说:

Exception of type
‘System.OutOfMemoryException’ was
thrown.

问题是如何打开此文件并逐行阅读.

>文件大小:564 MB(591,886,626字节)
>文件编码:UTF-8
>文件包含Unicode字符.

解决方法

您可以打开文件read it as a stream,而不是一次性将所有内容加载到内存中.

来自MSDN:

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user kNow what went wrong.
            Console.WriteLine("The file Could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐