简体   繁体   English

在csv中读取时,出现System.FormatException错误,但不确定原因

[英]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. 我是C#的新手,我编写了一个小测试应用程序,以了解我是否了解如何读取csv文件。

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 . 我创建了一个类来处理收到的数据,但是我的代码无法编译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. 由于values[0]可能不是有效的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. 您正在读取一行(很可能是最后一行),该行为空白, .split返回一个空字符串,并且在尝试转换时失败。

I would says #2 is your more likely culprit. 我会说#2是您更可能的罪魁祸首。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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