使用C#读取CSV文件 [英] Reading CSV files using C#
问题描述
我正在编写一个简单的导入应用程序,需要读取一个CSV文件,在 DataGrid
中显示结果,并在另一个网格中显示CSV文件的损坏行。例如,在另一个网格中显示短于5个值的线。我想这样做:
I'm writing a simple import application and need to read a CSV file, show result in a DataGrid
and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:
StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
row = line.Split(',');
importingData.Add(new Transaction
{
Date = DateTime.Parse(row[0]),
Reference = row[1],
Description = row[2],
Amount = decimal.Parse(row[3]),
Category = (Category)Enum.Parse(typeof(Category), row[4])
});
}
但在这种情况下很难对数组进行操作。有没有更好的方法来分割值?
but it's very difficult to operate on arrays in this case. Is there any better way to split the values?
推荐答案
不要重新发明轮子。利用.NET BCL中已有的功能。
Don't reinvent the wheel. Take advantage of what's already in .NET BCL.
- 添加对
Microsoft.VisualBasic
的引用(是的,它说VisualBasic,它在C#中工作也一样 - 记住,最后它只是IL) - 使用
Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV file
- add a reference to the
Microsoft.VisualBasic
(yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL) - use the
Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV file
以下是示例代码:
using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
}
}
}
它在我的C#项目中非常适合我。
It works great for me in my C# projects.
以下是一些更多链接/信息:
Here are some more links/informations:
- MSDN: Read From Comma-Delimited Text Files in Visual Basic
- MSDN: TextFieldParser Class
这篇关于使用C#读取CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!