如何使用 csvhelper c# 从 csv 文件中解析特定值

How to parse a specific value out of a csvfile uising csvhelper c#

我正在尝试使用 csvHelper 解析某个 csvFile。文件构成如下:

value: 333_345, nextval: 5578

val, 1val
200, 300

此 csv 文件的独特之处在于该行(值:333_345,nextval:5578)不是 headers 并且真正的 headers 直到该行才开始(val, 1val)

我知道到达 headers (val, 1val) 我可以直接调用跳过记录函数一直跳到那里。我的问题是,我如何才能从第一行获取值?

特别是这些(值:333_345,nextval:5578)

到目前为止我试过的是:

using (StreamReader reader = new StreamReader(@"path"))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Configuration.RegisterClassMap<FooMap>();//necessary for mapping 
                csv.Read();
                var records = csv.GetField(0);
            }
.
.
.

 public class Foo
    {
        [Index(0)]
        public string value { get; set; }


    }


    public class FooMap : ClassMap<Foo>
    {
        public FooMap()
        {
            Map(m => m.value).Index(0);

        }
    }

有了这个,通过将索引设置为 [0],我得到了第一行,但它以水平字符串的形式提供给我:

v
a
l
u
e
:
3
3
3
_
3
4
5

我需要做什么才能做到 return (333_345)?

您不需要同时使用属性和 class 映射。如果使用属性映射,则不需要注册 class 映射。

void Main()
{
    var s = new StringBuilder();
    s.AppendLine("value: 333_345, nextval: 55578");
    s.AppendLine();
    s.AppendLine();
    s.AppendLine("val, 1val");
    s.AppendLine("200, 300");
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Read();

        var val = csv.GetField(0);
        var nextval = csv.GetField(1);

        csv.Read();
        csv.ReadHeader();

        var records = csv.GetRecords<Foo>().ToList();

        records.Dump();
    }
}

public class Foo
{
    [Index(0)]
    public string Value { get; set; }
    [Index(1)]
    public string Value1 { get; set; }
}

注意:Dump() 是一个输出变量的 LINQPad 扩展。