C# 将分隔文件读入DataTable的高效函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1166272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:49:42  来源:igfitidea点击:

Efficient function for reading a delimited file into DataTable

c#.netfileimport

提问by AlteredConcept

I was wondering if anyone knew of an efficient c# function for reading a tab delimited file into a datatable?

我想知道是否有人知道将制表符分隔的文件读入数据表的高效 c# 函数?

Thanks

谢谢

回答by Steve

Here's one way to do it...

这是一种方法来做到这一点......

        var dt = new DataTable();
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));

        var lines = File.ReadAllLines(@"c:\tabfile.txt");
        foreach( string line in lines )
            dt.Rows.Add(line.Split('\t'));

回答by Arsen Mkrtchyan

public System.Data.DataTable GetDataTable(string strFileName)
{
    System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
    conn.Open();
    string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
    System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
    System.Data.DataSet ds = new System.Data.DataSet("CSV File");
    adapter.Fill(ds);
    conn.Close();
    return ds.Tables[0];
 }

回答by Matthew Whited

This currently uses the LINQ methods .First()and .Skip()both are easy to recreate if you need to use this on .Net 2.0

这当前使用 LINQ 方法.First().Skip()如果您需要在 .Net 2.0 上使用它,两者都很容易重新创建

//even cooler as an extension method
static IEnumerable<string> ReadAsLines(string filename)
{
    using (var reader = new StreamReader(filename))
        while (!reader.EndOfStream)
            yield return reader.ReadLine();
}

static void Main()
{
    var filename = "tabfile.txt";
    var reader = ReadAsLines(filename);

    var data = new DataTable();

    //this assume the first record is filled with the column names
    var headers = reader.First().Split('\t');
    foreach (var header in headers)
        data.Columns.Add(header);

    var records = reader.Skip(1);
    foreach (var record in records)
        data.Rows.Add(record.Split('\t'));
}