简体   繁体   中英

Validate header from CSV file when importing into Datatable c#

Shortly, i'm trying to import csv file into datatable. i'm adding columns like this

DataTable data = new DataTable();

data.Columns.Add("ID", typeof(string));
data.Columns.Add("Name", typeof(string)).MaxLength = 150;
data.Columns.Add("Last name", typeof(string));

and then:

using (var reader = new StreamReader(file.InputStream))
{

    DataRow row;

    var headers = reader.ReadLine();

    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        string[] value = line.Split(',');



        if (value.Length == data.Columns.Count)
        {
            row = data.NewRow();

            row.SetField(0, ParseInt(value[0]));
            row.SetField(1, value[1]);
            row.SetField(2, value[2]);



//and so on 
}

Please can help with a way to validate headers, if the hard-coded ones are the same as the imported file? PS the validation for length doesn't work very good. Sometimes, if the last columns in CSV are emty the last one is not counted.

Can't you just do a split on headers after you read the first line, then loop for the length of headers and check header value with the corresponding datatable column header?

If you have less headers in the file because the last column is empty that's fine because you won't have any data to add to that column in the data table, but checking like this should ensure that the value in a row in the data file will go into a column in the datatable where the name matches the header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM