如何在C#中打开一个大文本文件
我有一个包含大约100000篇文章的文本文件。 文件结构是:
.Document ID 42944-YEAR:5 。日期03 \ 08 \ 11 .Cat政治 文章内容1 .Document ID 42945-YEAR:5 。日期03 \ 08 \ 11 .Cat政治 文章内容2
我想在c#中打开这个文件,逐行处理它。 我试过这段代码:
String[] FileLines = File.ReadAllText( TB_SourceFile.Text).Split(Environment.NewLine.ToCharArray());
但它说:
抛出了类型’System.OutOfMemoryException’的exception。
问题是如何打开此文件并逐行阅读。
- 文件大小:564 MB(591,886,626字节)
- 文件编码:UTF-8
- 文件包含Unicode字符。
您可以打开文件并将其作为流读取,而不是一次性将所有内容加载到内存中。
来自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); } } }
您的文件太大,无法一次性读入内存,因为File.ReadAllText
正在尝试执行此操作。 您应该逐行读取文件。
改编自MSDN :
string line; // Read the file and display it line by line. using (StreamReader file = new StreamReader(@"c:\yourfile.txt")) { while ((line = file.ReadLine()) != null) { Console.WriteLine(line); // do your processing on each line here } }
这样,任何时候文件中只能有一行文件。
如果您使用的是.NET Framework 4,则System.IO.File上有一个名为ReadLines的新静态方法,它返回一个IEnumerable字符串。 我相信它被添加到这个确切场景的框架中; 但是,我还没有自己使用它。
MSDN文档 – File.ReadLines方法(String)
相关的堆栈溢出问题 – .net框架4.0的File.ReadLines(..)方法中的错误
像这样的东西:
using (var fileStream = File.OpenText(@"path to file")) { do { var fileLine = fileStream.ReadLine(); // process fileLine here } while (!fileStream.EndOfStream); }