读取大制表符分隔的txt文件的有效方法

本文关键字:文件 有效 方法 txt 读取 制表符 分隔 | 更新日期: 2023-09-27 17:57:09

我有一个制表符分隔的 txt 文件,其中包含 500K 条记录。我正在使用下面的代码将数据读取到数据集。使用 50K 时,它工作正常,但 500K 它给出"抛出类型为'System.OutOfMemoryException'的异常"。

读取大制表符分隔数据的更有效方法是什么?或者如何解决这个问题?请给我举个例子

public DataSet DataToDataSet(string fullpath, string file)
{
    string sql = "SELECT * FROM " + file; // Read all the data
    OleDbConnection connection = new OleDbConnection // Connection
                  ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";"
                   + "Extended Properties='"text;HDR=YES;FMT=Delimited'"");
    OleDbDataAdapter ole = new OleDbDataAdapter(sql, connection); // Load the data into the adapter
    DataSet dataset = new DataSet(); // To hold the data
    ole.Fill(dataset); // Fill the dataset with the data from the adapter
    connection.Close(); // Close the connection
    connection.Dispose(); // Dispose of the connection
    ole.Dispose(); // Get rid of the adapter
    return dataset;
}

读取大制表符分隔的txt文件的有效方法

TextFieldParser使用流方法 - 这样您就不会一次性将整个文件加载到内存中。

您确实希望枚举源文件并一次处理每一行。我使用以下

    public static IEnumerable<string> EnumerateLines(this FileInfo file)
    {
        using (var stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var reader = new StreamReader(stream))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }
然后,对于每一行

,您可以使用选项卡将其拆分并一次处理每一行。这样可以在解析时保持非常低的内存,仅当应用程序需要时才使用内存。

你试过TextReader吗?

  using (TextReader tr = File.OpenText(YourFile))
  {
      string strLine = string.Empty;
      string[] arrColumns = null;
      while ((strLine = tr.ReadLine()) != null)
      {
           arrColumns = strLine .Split(''t');
           // Start Fill Your DataSet or Whatever you wanna do with your data
      }
      tr.Close();
  }

我找到了FileHelpers

文件帮助程序是一个免费且易于使用的 .NET 库,用于从文件、字符串或流中的固定长度或分隔记录导入/导出数据。

也许它可以提供帮助。