Karthik
Karthik

Reputation: 2399

Issue with empty columns in tab delimited text file

i am trying to create a data table from a tab delimited text file.I am getting the values from the file easily.The problem is that when there is a empty column in text file same empty column is not created in data table instead the next non-empty column contents get replaced in the empty columns area

format of data in textfile

id    name    product    cost     company name


1      abc    shoe                   xxx
2      xyz    chain                  yyy

Data table obtained

id    name    product    cost     company name

1      abc     shoe       xxx
2      xyz     chain      yyy

my code to getdata

var reader = new StreamReader(File.OpenRead(@"d:\d.txt"));
        var table = new DataTable("SampleTable");
        string[] fieldValues = reader.ReadLine().Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < fieldValues.Length; i++)
        {
            table.Columns.Add(new DataColumn(fieldValues[i].ToString().Trim()));
        }
        while (!reader.EndOfStream)
        {

            var line = reader.ReadLine().Trim();
            var values = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            string[] ee = values;

            var newRow = table.NewRow();
            for (int i = 0; i < ee.Length; i++)
            {
                newRow[i] = ee[i].Trim().ToString(); // like sample [0,0]
            }
            table.Rows.Add(newRow);
        }

Upvotes: 3

Views: 2632

Answers (3)

Security Hound
Security Hound

Reputation: 2551

If you have an empty column, then you should read an empty string, not a null string.

In other words....

1,abc,shoe,,xxx

The reason your getting the result your getting is because of this: StringSplitOptions.RemoveEmptyEntries

Upvotes: 3

Stefan
Stefan

Reputation: 14880

The problem might be that you split the line with the RemoveEmptyEntries option:

var values = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

The empty cell gets removed. Omit this parameter and it should work...

Upvotes: 3

okrumnow
okrumnow

Reputation: 2416

You told Split to do exactly what you observe by setting the option StringSplitOptions.RemoveEmptyEntries - it removes empty entries.

Remove this option and it will keep the empty column.

Upvotes: 4

Related Questions