[英]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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.