简体   繁体   中英

Reading in a csv, getting System.FormatException error, but not sure why

I am new to C#, and I wrote a little test application to see if I understand how to read in a csv file.

I created a class to handle the data received, but my code will not compile : An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll .

Code below:

static void Main(string[] args)
        {
            var fileName = @"C:\Sample.csv";
            var file = new FileInfo(fileName);
            if (file.Exists)
            {
                List<Company> comp = new List<Company>();
                using (var reader = new StreamReader(File.OpenRead(fileName)))
                {
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var values = line.Split(',');


                        var companyobj = new Company()
                        {
                            Id = Convert.ToInt32(values[0]),
                            CompanyCode = values[1]
                        };
                        comp.Add(companyobj);

                        foreach (Company c in comp)
                        {
                            Console.WriteLine(c.Id + " "+c.CompanyCode);
                        }

                    }
                }

            }
        }

This is most likely happening on the following line:

Id = Convert.ToInt32(values[0]),

Since values[0] is probably not a valid int. Possible causes could be

  1. The value is a string which contains nonnumeric chars
  2. The you are reading a line (most likely the last line) which is blank and the .split is returning a blank string and failing when trying to convert.

I would says #2 is your more likely culprit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM