Skip to content

Instantly share code, notes, and snippets.

@pczajkowski
Created January 21, 2024 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pczajkowski/538d9164c93e9348124bddc74015ddb7 to your computer and use it in GitHub Desktop.
Save pczajkowski/538d9164c93e9348124bddc74015ddb7 to your computer and use it in GitHub Desktop.
CsvHelper vs Sep in the land of bad CSVs
namespace CSVHelperVsSep;
public class Comparison
{
public string? Original;
public string? Sep;
public string? CsvHelper;
}
We can make this file beautiful and searchable if this error is corrected: Illegal quoting in line 8.
a,True
"",True
"""",True
"""""",True
"a",True
"a""a",True
"a""a""a",True
a""a,False
a"a"a,False
"" ,False
"a" ,False
"",False
"a",False
a"""a,False
"a"a"a",False
"" ,False
"a" ,False
"a"""a,False
"a"""a",False
""a",False
"a"a",False
""a"a"",False
""",False
""""",False
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
using CSVHelperVsSep;
using nietras.SeparatedValues;
const string testFile = "./forTest.csv";
var testString = File.ReadAllText(testFile);
var split = testString.Split('\n').Select(x => x.Split(',').First());
var comparisons = split.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => new Comparison { Original = s }).ToList();
using var reader = new StringReader(testString);
var configuration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Mode = CsvMode.NoEscape,
HasHeaderRecord = false
};
using var csvHelper = new CsvReader(reader, configuration);
var index = 0;
Console.WriteLine("CSVHelper");
while (csvHelper.Read())
{
comparisons[index].CsvHelper = csvHelper.GetField(0);
Console.WriteLine($"{index}: `{comparisons[index].Original}` - `{comparisons[index].CsvHelper}` - {(comparisons[index].Original.Equals(comparisons[index].CsvHelper) ? "Pass" : "Fail")}");
index++;
}
index = 0;
Console.WriteLine("Sep");
try
{
using var sep = Sep.Reader(o => o with { HasHeader = false, Unescape = true, CultureInfo = CultureInfo.InvariantCulture}).FromText(testString);
foreach (var readRow in sep)
{
comparisons[index].Sep = readRow[0].ToString();
Console.WriteLine(
$"{index}: `{comparisons[index].Original}` - `{comparisons[index].Sep}` - {(comparisons[index].Original.Equals(comparisons[index].Sep) ? "Pass" : "Fail")}");
index++;
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed at index {index}: {ex.Message}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment