您好,我正在学习如何解析由逗号,制表符和/或\
分隔的文本文件。文本如下:
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提示很有帮助,而且我不再遇到字符串输入错误...。但是,在解析文件之后,我仍然没有得到任何返回的行 enter image description here
答案 0 :(得分:0)
您正在尝试将非数字字符串(“福特”)转换为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]);
答案 1 :(得分:0)