首页 > 解决方案 > 我正在尝试解析由 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 sugestion 有帮助,我不再有字符串输入错误....如何在文件被解析后我仍然没有得到任何行在 此处输入图像描述

标签: c#

解决方案


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

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

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

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

推荐阅读