简体   繁体   English

如何使用 CSV Helper 在 C# 中逐行读取?

[英]How to use CSV Helper to read line by line in c#?

So this is the code I am using currently, but I don't specifically want to create my own reader.所以这是我目前使用的代码,但我并不特别想创建自己的阅读器。 My problem is that I want to read a full csv file line by line, but the file contents will change from time to time, so it has to be generic.我的问题是我想逐行读取一个完整的 csv 文件,但文件内容会不时发生变化,所以它必须是通用的。

This is what I am using currently,这是我目前使用的

try
{
    var Lines = File.ReadAllLines(path);
    var csvRawData = from line in Lines select (line.Split(',')).ToArray();
    var csvData = csvRawData.ToList();
    return csvData;
}
catch (Exception ex)
{                
    MessageBox.Show(ex.Message);
    Logger.Log(ex.Message, true);
    return null;
}

The return csvData is of type List.返回的 csvData 是 List 类型。 I then just separate the content out from it manually.然后我只是手动将内容从中分离出来。

Here is an example of reading line by line, where the second line has a different 'type' then the first line:这是逐行阅读的示例,其中第二行与第一行具有不同的“类型”:

    using (StreamReader reader = new StreamReader(filePath))
    {
        using (CsvReader csv = new CsvReader(reader))
        {
            csv.Read();

            Type1 sample = new Type1();
            sample.Id = csv.GetField<int>(0);
            sample.Lines = csv.GetField<int>(1);

            csv.Read();

            Type2 sample2 = new Type2();
            sample2.Angle = csv.GetField<double>(0);
            sample2.Distance = csv.GetField<int>(1);
        }
    }

You say CsvHelper , but from your code it doesn't look like you're actually using it.您说CsvHelper ,但从您的代码来看,您实际上并未使用它。 If you are using it, you can use the GetField methods to pull a field by header name of index.如果您正在使用它,您可以使用GetField方法通过索引的标题名称提取字段。 Take a look at the documentation for more information on how to use it.查看文档以获取有关如何使用它的更多信息。
https://joshclose.github.io/CsvHelper/examples/reading/ https://joshclose.github.io/CsvHelper/examples/reading/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM