我正在努力完成一项学校作业,让我们使用C#程序解析CSV文件中的数据并将其添加到本地数据库中的表中。当我尝试运行程序时,我使用的方法无法将任何数据解析到对象中。
以下是我使用的方法:
//Parse CSV line
public bool ParseCSVline(string aLine)
{
try
{
string[] fields = aLine.Split(',');
this.Item_ID = int.Parse(fields[0]);
this.Invent_id = int.Parse(fields[1]);
this.Itemsize = fields[2];
this.Color = fields[3];
this.Curr_price = decimal.Parse(fields[4]);
this.Qoh = int.Parse(fields[5]);
return true; //if everything parsed, return true
}
catch (Exception ex)
{
Console.Write("Failed to Parse");
return false; //if a parse failed, return false
}
运行程序时,该方法不断抛出异常而不是实际解析数据。为清楚起见,这是主程序中调用所有内容的部分:
/Step 2 - Open input file
//Set where the file comes from
string filepath = @"C:\Users\Karlore\Documents\School\SAI-430\";
string filename = @"NewInventory.csv";
//Open reader
StreamReader theFile = new StreamReader(filepath + filename);
//Step 3 - Create an object to use
Item theItem = new Item();
//Step 4 - Loop through file and add to database
while (theFile.Peek() >= 0)
{
//Get one line and parse it inside the object
theItem.ParseCSVline(filename);
//Check to see if item is already there
if (theItem.IsInDatabase(connection))
{
continue;
}
else
{
//Add the new item to the database if it wasn’t already there
theItem.AddRow(connection);
}
} //end of while loop
如果有人能指出我可能犯错误的地方,或指出我正确的方向,我将不胜感激。
答案 0 :(得分:0)
替换行:
theItem.ParseCSVline(filename);
由:
theItem.ParseCSVline(theFile.ReadLine());