c# - 我正在尝试解析由 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 有帮助,我不再有字符串输入错误....如何在文件被解析后我仍然没有得到任何行在 此处输入图像描述
解决方案
您正在尝试将非数字字符串(“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]);
推荐阅读
- javascript - sequelize.literal 返回原始属性名称和重命名后的属性
- sql - 如何计算另一个表中连接查询的结果值?
- php - 在 woocommerce 上为免费物品创建运输方式
- excel - 在 VBA 中使用 selection.currentregion 在另一张表中进行 vlookup
- python - python如何在交互式解释器与jupyter笔记本中实习字符串
- mysql - 有没有一种解决方案可以在没有左连接的情况下从 2 个表中获取数据?
- c++ - 我可以在 main 之前创建 fstream 吗?
- ios - 如何在 iOS 14 中更改 UIPickerView 的选定色调颜色?
- python - 如何在循环中编写 DataFrames 到 excel
- linux - 使用 Sed 替换字符串?