簡體   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