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

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

问题描述

我正在编写一个简单的导入应用程序,需要读取 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 a 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 类解析 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

这是示例代码:

using (TextFieldParser parser = new TextFieldParser(@"c:	emp	est.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:

这篇关于使用 C# 读取 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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