【问题标题】:Reading and Parsing Files in .NET - Performance For Hire在 .NET 中读取和解析文件 - 招聘性能
【发布时间】:2008-10-29 14:44:52
【问题描述】:

我想要读取和解析文件的最高效方式。

是否可以在 .NET 中读取文件,但不能将整个文件加载到内存中?即在我解析每一行的内容时逐行加载文件?

XmlTextReader 是将整个文件加载到内存中,还是在读取文件时将文件流式传输到内存中?

【问题讨论】:

  • 最佳性能 = 最佳性能

标签: .net performance file


【解决方案1】:

您可以使用 StreamReader 类的 ReadLine 方法:

string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
}

file.Close();

对于 XML 文件,我会使用 XMLTextReader。看到这个article on Dr. Dobb's Journal

使用 C# 在 .NET 中解析 XML 文件: .NET 中有五种不同的解析技术,每一种都有自己的优势”

【讨论】:

    【解决方案2】:

    XmlTextReader 在流上工作 - 因此它不会读取内存中的整个文件。

    【讨论】:

      【解决方案3】:

      这是我多年来一直在使用的 TextFileReader 类

      http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f

      【讨论】:

        【解决方案4】:

        我不确定 XMLTextReader,但您可以使用 FileReader 对象逐行读取文件。 )

        【讨论】:

          【解决方案5】:

          您可以尝试使用 StreamReader.ReadLine 函数并测试与 FileStream/TextReader 等相比的性能。

          【讨论】:

          • StreamReader 继承自 TextReader(抽象类),因此无法比较它们的性能。
          • 好电话,没有意识到这一点。
          【解决方案6】:

          我也不确定 XMLTextReader,但您可以像这样逐行阅读:

          Dim theLine as String
          Dim fsFile As New FileStream(inputFile, FileMode.Open)   'File Stream for the Input File
          Dim fsImport As New FileStream(outputFile, FileMode.OpenOrCreate)  'File Stream for the Output File
          Dim srFile As New StreamReader(fsFile)  'Stream Reader for Input File
          Dim swfile As New StreamWriter(fsImport)   'Stream Writer for Output File
          
          Do While srFile.Peek <> -1              'Do While it's not the last line of the file
              theLine = srFile.ReadLine           'Read the line
              Messagebox.Show(theLine, "Line-by-Line!")
          Loop
          

          【讨论】:

            【解决方案7】:

            XmlTextReader 不会将整个文件加载到内存中,它对流进行操作。

            所有文件流对象都以“块”的形式读取文件。 您可以指定每次调用(即 m 字节,其中 m 是任何整数 - 可能是长 - 值,或使用文本阅读器,任意长度的单行)带回程序的数据量(即块有多大) ) 出于性能原因,操作系统将在每次读取时缓存 n 个字节(其中 n 部分或全部为 0)。 你完全无法控制 n 的大小,只会让你自己尝试找出它是什么而感到沮丧,因为它会因一千种不同的环境因素而变化。

            【讨论】:

            • 问题似乎没有根据级别进行标记?为了有效,您在提交简单中等难度初学者高级大师级别等问题时需要一个内置评分系统。
            • 他只是担心二进制文件。
            猜你喜欢
            • 2013-09-09
            • 1970-01-01
            • 2023-04-02
            • 2010-12-20
            • 2011-01-29
            • 1970-01-01
            • 1970-01-01
            • 2010-09-16
            • 2012-10-29
            相关资源
            最近更新 更多