繁体   English   中英

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

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

嗨,我正在学习如何解析由逗号,制表符和/或\\分隔的文本文件。

文本如下所示:

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

我的代码如下所示:

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; }
    }
}

我得到的结果如下:

在此处输入图片说明

我不太明白我做错了什么


mmathis提示已提供帮助,并且我不再遇到字符串输入错误....在解析了文件之后,如何仍然没有返回任何行在这里输入图像描述

您正在尝试将非数字字符串(“福特”)转换为int

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

C#中的索引从0开始,因此索引1将是数组中的第二项。 您的架构指示这是“ Make”。 您需要将行更改为

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

您可能还需要调整其他列的其他索引:

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]);

对于这种情况,最好的方法是调试应用程序并查看代码中正在发生什么。 继续,我的意思是逐步分析您的循环和转换逻辑。 例如,在您的代码中,循环的第一次运行给出以下结果:

在此处输入图片说明

在第二次运行中,调试时显示以下结果: 在此处输入图片说明

因此,基本上,如果您能够理解Visual Studio中的调试过程,它将帮助您查明逻辑错误,并可以根据需要解决它们。

在您的情况下,您尝试解析的索引与前两次运行不同,因此您将获得异常。 您需要确定您的逻辑,以确保所有索引都属于解析过程的每次运行的正确类别。

暂无
暂无

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

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