Aug 20, 2014

Reading a tab delimited text file into DataTable

Reading a tab delimited text file into DataTable


DataTable records = new DataTable("records");
var textReader = new TextFieldParser(@"E:\CSV.txt");
using (textReader)
{
    textReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
    textReader.Delimiters = new String[] { "\t" };

    List currentRow = new List();

    bool IsFirst = true;
    int rowCount = 0;
    while (!textReader.EndOfData)
    {
        try
        {
            Console.WriteLine("reading line: " + (rowCount++));
            currentRow = textReader.ReadFields().ToList();
            if (IsFirst)
            {
                IsFirst = false;
                //add columns
                foreach (string col in currentRow)
                {
                    records.Columns.Add(col);
                }
            }
            else
            {
                DataRow row = records.NewRow();
                for (int i = 0; i < currentRow.Count; i++)
                {
                    row[i] = currentRow[i];
                }
                records.Rows.Add(row);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}


PS: You need to add reference to Microsoft.VisualBasic also import the namespace using Microsoft.VisualBasic.FileIO;

No comments:

Post a Comment

Be the first to comment on this post.