Read Streamreader First Line or skip how to fix?

Asked

Viewed 365 times

3

I have a file. csv and tou put the data in a datatable , but the problem I have at the moment is that it does not pass this data due to the first line it reads from the second column being of the integer type (and the first value of this 2 column is ATID (Header)) the rest of that column are whole and I can’t fix it. I’ve already tried a conversion and it still doesn’t work. dr["Atid"] = Convert.Toint32(lineitems1);

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

File example

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);
                }

        }

Erro/Debug

1 answer

5

A solution for this line, and perhaps for others who may have invalid content, and check the conversion, for example using TryParse

If the return is true because it managed 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);
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.