我有這段代碼來讀取一個csv文件並將這些字段存儲在'Records'類的objects_Records列表中。C#Lumenworks Csvreader-在讀取包含空/空字段的csv文件時在消息框中顯示錯誤
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
附加信息:輸入字符串格式不正確。
請幫助我解決可以處理該異常的異常處理機制。
您需要向我們展示一個示例文件。哪些單元格是空的?如果它是其中一個數字字段,請將'Double.Parse'更改爲['double.TryParse()'](http://msdn.microsoft.com/zh-cn/library/994c0zb1%28v=vs.110%29 .aspx)並處理錯誤。 – dbc 2014-11-01 22:03:27
是的。當我使用double.TryParse()方法來處理數值時會處理異常。但是對於字符串值沒有這種方法的必要性。我想知道爲什麼? – Madhur 2014-11-03 07:45:54