I have to parse a TSV file which has the following structure: [Secti "1 2" "2 3"his?
Asked
Active
Viewed 414 times
-1
-
2Not sure why this was downvoted, but it probably has to do with using an image instead of formatted text for the sample data. – Joel Coehoorn Aug 03 '21 at 14:33
-
Possible duplication of https://stackoverflow.com/questions/60474975/csvhelper-does-not-parse-my-tab-delimited-csv-file Either way, in the reader configuration you can set the delimiter to be anything you want, in your case "\t" – Br4infreze Aug 03 '21 at 14:34
-
I manage to set the CSV info as a code. Thank you! – PAVEL-ALEXANDRU BAJENARU Aug 03 '21 at 19:36
-
Are `[Section one of info]` and `[Section two of info]` part of the CSV file? If not, is there any delimiter between the two sections? Also, is it true that each entire row is bracketed in double-quotes like so? `"1 2"`? – dbc Aug 03 '21 at 22:16
-
@dbc yeap they are aprt of the CSV file and regarding the double-quotes this is what I get when I try open the file with Notepad – PAVEL-ALEXANDRU BAJENARU Aug 04 '21 at 05:16
1 Answers
1
I'm not sure if this is what you were trying to do or not. I also noticed that it appeared to be 4 spaces between records. If it is actually a tab, you can change the delimiter to a tab Delimiter = "\t",
void Main()
{
var data = @"[Section one of info]
""Atr1 1""
""Atr2 2""
[Section two of info]
""Atr3 Atr4""
""1 2""
""2 3""
""4 5""";
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = " ",
Mode = CsvMode.Escape
};
using (var reader = new StringReader(data))
using (var csv = new CsvReader(reader, config))
{
var isSectionOne = true;
var record = new Foo() { Atr3 = new List<int>(), Atr4 = new List<int>() };
while(csv.Read())
{
if (csv.GetField(0).StartsWith("["))
continue;
if (isSectionOne)
{
if (csv.GetField(0) == "Atr1")
{
record.Atr1 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr2")
{
record.Atr2 = csv.GetField<int>(1);
}
if (csv.GetField(0) == "Atr3")
{
isSectionOne = false;
}
}
else
{
record.Atr3.Add(csv.GetField<int>(0));
record.Atr4.Add(csv.GetField<int>(1));
}
}
record.Dump();
}
}
public class Foo
{
public int Atr1 { get; set; }
public int Atr2 { get; set; }
public List<int> Atr3 { get; set; }
public List<int> Atr4 { get; set; }
}

David Specht
- 7,784
- 1
- 22
- 30