【问题标题】:How to parse a specific value out of a csvfile uising csvhelper c#如何使用 csvhelper c# 从 csv 文件中解析特定值
【发布时间】:2020-06-05 22:32:09
【问题描述】:

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

value: 333_345, nextval: 5578

val, 1val
200, 300

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

我知道到达标题 (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

我需要做什么才能让它返回 (333_345)?

【问题讨论】:

  • 行为空或行包含冒号时使用 StreamReader 读取。然后开始解析 CSV 数据。

标签: c# csv parsing csvhelper


【解决方案1】:

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

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 扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多