阅读使用C#的CSV文件 [英] Reading CSV files using C#

查看:117
本文介绍了阅读使用C#的CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的进口申请,并需要读取一个CSV文件,结果显示在另一个网格中的CSV文件的的DataGrid 并显示损坏的行。例如,显示在另一个网格短于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基础类库的优势。

Don't reinvent the wheel. Take advantage of what's already in .NET BCL.


  • 添加到 Microsoft.VisualBasic程序引用(是的,它说的VisualBasic,但它在C#中的作品一样好 - 请记住,在结束这一切只不过是IL)

  • 使用 Microsoft.VisualBasic.FileIO.TextFieldParser 类来分析CSV文件

  • 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

下面是示例code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆