来自文本文件的数据表? [英] DataTable from TextFile?

查看:22
本文介绍了来自文本文件的数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我接手了另一个开发人员编写的应用程序,该应用程序从数据库中读取数据并将其导出.

I have taken over an application written by another developer, which reads data from a database, and exports it.

开发人员使用了 DataTables 和 DataAdaptors.

The developer used DataTables and DataAdaptors.

所以,

 _dataAdapter = new SqlDataAdapter("Select * From C....", myConnection);

然后

ExtractedData = new DataTable("CreditCards");
_dataAdapter.Fill(ExtractedData);

ExtractedData 然后被传递来执行不同的功能.

ExtractedData is then passed around to do different functions.

现在有人告诉我,除此之外,我还需要从一些逗号分隔的文本文件中获取相同格式的数据.该应用程序执行相同的处理 - 它只是从两个来源获取数据.

I have now been told that I need to, in addition to this, get the same format of data from some comma separated text files. The application does the same processing - it's just getting the data from two sources.

所以,我想知道是否可以将数据读入 DataTable,如上所述,然后从 CSV 文件添加更多记录.

So, I am wondering if I can get the data read into a DataTable, as above, and then ADD more records from a CSV file.

这可能吗?

推荐答案

您可能需要使用此函数将数据从文件读入 DataTable.

You might need to use this function to read the data into DataTable from the file.

public DataTable GetDataSourceFromFile(string fileName)
{
    DataTable dt = new DataTable("CreditCards");
    string[] columns = null;

    var lines = File.ReadAllLines(fileName);

    // assuming the first row contains the columns information
    if (lines.Count() > 0)
    {
        columns = lines[0].Split(new char[] { ',' });

        foreach (var column in columns)
            dt.Columns.Add(column);
    }

    // reading rest of the data
    for (int i = 1; i < lines.Count(); i++)
    {
        DataRow dr = dt.NewRow();
        string[] values = lines[i].Split(new char[] { ',' });

        for (int j = 0; j < values.Count() && j < columns.Count(); j++)
            dr[j] = values[j];

        dt.Rows.Add(dr);
    }
    return dt;
}

这篇关于来自文本文件的数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆