I am trying to parse a certain csvFile using csvHelper. The file constitutes as follows:
value: 333_345, nextval: 5578
val, 1val
200, 300
What makes this csv file unique is that the line (value: 333_345, nextval: 5578) are not headers and that the real headers do not start until the line (val, 1val)
I know that get to the headers (val, 1val) i can just call skip record function to jump all the way down there. My question is, how would I be able to get the values from the first line?
Specifically these ones(value: 333_345, nextval: 5578)
What ive tried so far is this:
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);
}
}
With this, by setting the index to [0], i get the first line, but it gives it to me in a horizontal string:
v
a
l
u
e
:
3
3
3
_
3
4
5
what would I have to do for it to just return (333_345)?
You don't need to use both attribute and class mapping. If you use attribute mapping, you don't need to register a class map.
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; }
}
note: Dump()
is a LINQPad extension that outputs the variable.