简体   繁体   中英

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

You are trying to convert a non-numeric string ("Ford") to an int :

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

Indexing in C# starts at 0, so index 1 will be the second item in the array. Your schema indicates this is "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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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