有效的方式来读取大型制表符分隔的txt文件?

Mic*_*orn 5 c# file-io tab-delimited

我有一个带有500K记录的制表符分隔的txt文件.我正在使用下面的代码将数据读取到数据集.使用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;
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 8

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

  • @hemp:可能是“麻烦且缓慢”。但它确实有效,并且避免了您使用手写分隔文本文件解析器遇到的许多问题。任何一天我都会选择“麻烦且缓慢,但有效”而不是“快速且有缺陷”。 (2认同)