我有这段代码来读取 csv 文件并将字段存储在“记录”类的 objects_Records 列表中。
private String text2,text3,text4,text5,text6;
private double text7,text8,text9;
private int text1;
private int count = 0;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "CSV files (*.csv)|*.csv"; // Show only .csv files among all the different files
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
String file = openFileDialog1.FileName;
try
{
textBoxFilePath.Text = file;
using (CsvReader csv = new CsvReader(new StreamReader(file), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
count += 1;
for (int i = 0; i < fieldCount; i++)
{
switch (headers[i].ToLower())
{
case "plot":
text1 = int.Parse(csv[i]);
break;
case "local name":
text2 = csv[i];
break;
case "botanical name":
text3 = csv[i];
break;
case "genera":
text4 = csv[i];
break;
case "species":
text5 = csv[i];
break;
case "family":
text6 = csv[i];
break;
case "dbh":
text7 = Double.Parse(csv[i]);
break;
case "ba(sqm)":
text8 = Double.Parse(csv[i]);
break;
case "ba":
text8 = Double.Parse(csv[i]);
break;
case "height":
text9 = Double.Parse(csv[i]);
break;
default:
MessageBox.Show("Please check the column headers of the fields once!");
continue;
}
}
object_Records.Add(new Records(text1, text2, text3, text4, text5, text6, text7, text8, text9));
}
}
textBox1.Text = count.ToString();
}
catch (IOException)
{
}
}
}
对于没有“NULL/EMPTY”字段的 csv 文件,我的代码运行良好。遇到包含“NULL”字段的 csv 文件时会引发异常。
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
附加信息:输入字符串的格式不正确。
请帮助我解决可以处理该异常的异常处理机制。