我正在使用C#开发一个小应用程序,它将csv文件转换为可读格式。
以下是CSV文件中的示例
"Symbol","Date","Expiry","Strike Price","Open","High","Low","Close","LTP"
"5000","6000","4500","45855" ............
超过300行像这样。
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();
try
{
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(','); // <<< this ',' is not working
parsedData.Add(row);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return parsedData;
}
根据数据,我应该在LTP获得新的一行,但它没有发生,并且超过我得到的结果作为单行。如果添加列表即parseData,则显示为单行。
答案 0 :(得分:2)
正如其他人所说,滚动你自己的CSV解析器很困难且容易出错。我个人的偏好在于FileHelpers库,并向您展示我是多么好和容易,我已经包含了您的数据的工作示例:
using System;
using FileHelpers;
namespace ConsoleApplication1
{
internal class Program
{
public static void Main()
{
/*
Sample data from TestData.csv
"Symbol","Date","Expiry","StrikePrice","Open","High","Low","Close"
"MSF","20090913","03032012","1.233","1.1","14.54","0.07","14.11"
"APL","20111225","31122011","30.09","31.1","33.33","29.11","33.13"
*/
var engine = new FileHelperEngine<StockModel>();
engine.Options.IgnoreFirstLines = 1; // skip the header line
StockModel[] stocks = engine.ReadFile(@"TestData.csv");
Console.Read();
}
}
[DelimitedRecord(",")]
public class StockModel
{
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
public string Symbol;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Date;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Expiry;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Decimal, ".")]
public decimal StrikePrice;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Decimal, ".")]
public decimal Open;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Decimal, ".")]
public decimal High;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Decimal, ".")]
public decimal Low;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldConverter(ConverterKind.Decimal, ".")]
public decimal Close;
}
}
答案 1 :(得分:-2)
您的代码按预期工作。只需复制/粘贴它,它就会返回一个包含2个元素的列表,每行一个元素。每个元素都是一个字符串数组,第一个元素有9个元素,第二个元素有4个。
关于“停止重新发明轮子”,我个人不同意。解析CSV文件是一个简单的过程,您只需逐行阅读并调用.Split(delimiter)
即可。如果这样一个简单的过程需要一个特定的库,那么每个项目都会有500多个依赖项。
如果您没有特殊要求,例如多个分隔符,异步解析或您自己的代码尚未支持的任何内容,我将不会使用lib。
记住使用lib还会在项目中引入许多潜在的问题(许可证问题,可测试性,代码的可扩展性,这通常不是因为你没有代码,可移植性,错误......)。