简体   繁体   English

我正在尝试解析C#中以逗号分隔的文本文件

[英]I am trying to parse a text file delimited by commas in C#

Hi I am learning how to parse text files that are delimited by commas, tabs and/or \\ 嗨,我正在学习如何解析由逗号,制表符和/或\\分隔的文本文件。

the text looks like this: 文本如下所示:

Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

And my code looks like this : 我的代码如下所示:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T_2050_ParserEduardo
{
  class Program
  {
    static void Main(string[] args)
    {
        //Year,Make,Model,Description,Price
        //1997,Ford,E350,"ac, abs, moon",3000.00

        Console.WriteLine("Paser con Comas");

        /*
         * Pasos
         * Crear List<clsDetalle>
         * Leer archivo en una secuencia de lines con File.ReadAllLines()
         * Para cada linea, hacer el split correspondiente
         * Manualmente convertir los valores
         */

        List<clsCarro> resp = new List<clsCarro>();
        var lines = File.ReadAllLines("d:\\ztemp\\parserExEdu.txt");
        for (int i = 1; i < lines.Count(); i++)
        {
            try
            {
                var campos = lines[i].Split(',');
                clsCarro nR = new clsCarro();
                nR.Anio = Convert.ToInt32(campos[1]);
                nR.Fabricante = (String.IsNullOrEmpty(campos[2])) ? "" : 
                campos[2];
                nR.Modelo = (String.IsNullOrEmpty(campos[3])) ? "" : 
                campos[3];
                nR.Descripcion = (String.IsNullOrEmpty(campos[4])) ? "" : 
                campos[4];
                nR.Precio =  Convert.ToDouble(campos[5]);

            }
            catch (Exception ex)
            {

                Console.WriteLine("error en la fila {0}: {1}", i, 
                ex.Message);
                continue;
            }
        }
        Console.WriteLine("Parser terminado, tenemos {0} filas", resp.Count);
        Console.ReadLine();

      }
    }

   class clsCarro
   {
    public int Anio { get; set; }
    public string Fabricante { get; set; }
    public string Modelo { get; set; }
    public string Descripcion { get; set; }
    public double Precio { get; set; }
    }
}

And the Result I get is the following: 我得到的结果如下:

在此处输入图片说明

I do not quite understand what have I've done wrong 我不太明白我做错了什么


mmathis sugestion has helped and I no longer have the string input error.... how ever I still getting no rows in return after the file has been parsed enter image description here mmathis提示已提供帮助,并且我不再遇到字符串输入错误....在解析了文件之后,如何仍然没有返回任何行在这里输入图像描述

You are trying to convert a non-numeric string ("Ford") to an int : 您正在尝试将非数字字符串(“福特”)转换为int

nR.Anio = Convert.ToInt32(campos[1]);

Indexing in C# starts at 0, so index 1 will be the second item in the array. C#中的索引从0开始,因此索引1将是数组中的第二项。 Your schema indicates this is "Make". 您的架构指示这是“ Make”。 You need to change the line to 您需要将行更改为

nR.Anio = Convert.ToInt32(campos[0]);

You'll probably want to adjust the other indices for the other columns as well: 您可能还需要调整其他列的其他索引:

nR.Anio = Convert.ToInt32(campos[0]);
nR.Fabricante = (String.IsNullOrEmpty(campos[1])) ? "" : 
      campos[1];
nR.Modelo = (String.IsNullOrEmpty(campos[2])) ? "" : 
      campos[2];
nR.Descripcion = (String.IsNullOrEmpty(campos[3])) ? "" : 
      campos[3];
nR.Precio =  Convert.ToDouble(campos[4]);

For such cases, the best way is to debug your application and see what is going on in your code. 对于这种情况,最好的方法是调试应用程序并查看代码中正在发生什么。 By going on, I mean do a step by step analysis of your loops and conversion logic. 继续,我的意思是逐步分析您的循环和转换逻辑。 For example in your code, the first run of your loop gives the following result: 例如,在您的代码中,循环的第一次运行给出以下结果:

在此处输入图片说明

In your second run, the following result is shown on debugging: 在第二次运行中,调试时显示以下结果: 在此处输入图片说明

So basically if you were able to understand the debugging process in Visual Studio, it is going to help you pinpoint your logical errors and you would be able to resolve them as per your need. 因此,基本上,如果您能够理解Visual Studio中的调试过程,它将帮助您查明逻辑错误,并可以根据需要解决它们。

In your case, the indices that you are trying to parse are different as seen in the first two runs, hence you are getting the exceptions. 在您的情况下,您尝试解析的索引与前两次运行不同,因此您将获得异常。 You need to make your logic certain that all indices fall in the correct category for each run of your parsing process. 您需要确定您的逻辑,以确保所有索引都属于解析过程的每次运行的正确类别。

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

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