Read Streamreader First Line or skip how to give fix?

3

I have a .csv file and I call the data in a datatable, but the problem I have at the moment is that it does not pass this data because the first line that reads from the second column is of type integer (and the first value of this 2 column is ATID (Header)) the rest of this column are integers and I can not fix this. I already tried to do a conversion and it still does not give. dr ["AtId"] = Convert.ToInt32 (lineitems 1 );

Error: System.ArgumentException: 'Input string was not in a correct format.Couldn't store < # assetId # > in AtId Column. Expected type is Int32. '

Sample file

PPID; ATID

asd; 1

asd; 2

asd; 3

dsa; 4

erf; 5

      using (StreamReader sr = new StreamReader(@"C:PATHFILE...."))
        {
            var datatable = new DataTable();
            datatable.Columns.Add("PPId", typeof(string));
            datatable.Columns.Add("AtId", typeof(int));
            string line;


                while ((line = sr.ReadLine()) != null)
                {
                   sr.ReadLine().Skip(1);
                    System.Diagnostics.Debug.WriteLine(line + "\n");
                    string[] lineitems = line.Split(";");
                    DataRow dr = datatable.NewRow();
                    dr["PPId"] = lineitems[0];
                    dr["AtId"] = Convert.ToInt32(lineitems[1]); 
                    datatable.Rows.Add(dr);
                }

        }

    
asked by anonymous 22.08.2018 / 02:18

1 answer

5

A workaround for this line, and perhaps for others that may have invalid content, and verify the conversion, for example using TryParse

If the return is true because it was able to convert, otherwise you skip the line:

        while ((line = sr.ReadLine()) != null)
        {
            int num;
            sr.ReadLine().Skip(1);
            System.Diagnostics.Debug.WriteLine(line + "\n");
            if (!Int32.TryParse(lineitems[1], out num))
            {
                 continue; // pula para a próxima linha
            }
            string[] lineitems = line.Split(";");
            DataRow dr = datatable.NewRow();
            dr["PPId"] = lineitems[0];
            dr["AtId"] = num;  // número convertido 
            datatable.Rows.Add(dr);
        }
    
22.08.2018 / 02:29