Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#-无法解析CSV文件的方法_C#_Csv - Fatal编程技术网

c#-无法解析CSV文件的方法

c#-无法解析CSV文件的方法,c#,csv,C#,Csv,我正在努力完成一项学校作业,该作业要求我们使用C#程序解析CSV文件中的数据,并将其添加到本地数据库的表中。但是,当我尝试运行程序时,我使用的方法无法将任何数据解析到对象中 以下是我正在使用的方法: //Parse CSV line public bool ParseCSVline(string aLine) { try { string[] fields = aLine.Split(','); t

我正在努力完成一项学校作业,该作业要求我们使用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
如果有人能指出我可能犯了错误的地方,或者给我指出了正确的方向,我将不胜感激。

更换线路:

theItem.ParseCSVline(filename);
作者:


您正在将文件名传递给解析函数。您需要从文件中读取一行文本并将其传递。若要在将来进行故障排除,您可以使用异常处理。我会使用Console.Write(“它坏了”+ex.Message)。我认为ex.ToString()可能会提供更多信息,但我倾向于从提示开始☺谢谢你,塞西里奥。我必须学会如何快速做到这一点。这门课让我们以一种非常奇怪的方式学习C#,如此明显的事情对我来说并不那么明显。
file.ReadLine()
应该让您开始学习。Dotnetperls有很好的简单C#示例。这是他们的csv阅读器谢谢!这帮助我更好地理解StreamReader的功能。
theItem.ParseCSVline(theFile.ReadLine());