irham dollah
irham dollah

Reputation: 169

Why certain row shows different column's data in c#?

I want to write certain column from input file to the output file. My code looks like this:

try
        {
            using (StreamWriter file = new StreamWriter(@"outputfile.csv", true))
            {
                string[] lines;
                file.WriteLine("Date,Entity, ProdFamily, ProdGroup, ProdType1, ProdTypo, ProdType, Currency, InternalFlag, B/S");
                lines = System.IO.File.ReadAllLines(@"inputfile.csv";
                    foreach (string line in lines)
                    {
                        if (line != lines[0])
                        {   
                            string[] values = line.Split(',');
                            file.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
                                    values[43], values[0], values[11], values[12], values[13], values[15], values[14], values[28], values[22], values[9]);                  
                        }
                    }
            }
        }

The error I get is some of the row are showing other column's data. For example, the first column of the first row shows N when it should shows 1-Jun-20.

enter image description here

This is the part of input file that is being used for example above.

enter image description here

I try to hardcode by changing the column index for the defect row such as changing values[43] to values[43+2] but it just creates another unexpected data. Please help me.

Upvotes: 0

Views: 37

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156544

Your input file has commas in some of the cells: enter image description here

In the CSV, that will be represented like:

...,BL,"BR BSS PLC,WB,",NA,...

Your splitting code treats each of those commas equally, without accounting for whether they're being quoted or not:

string[] values = line.Split(',');

You should use a CSV Parsing library instead of trying to parse it yourself.

Upvotes: 2

Related Questions