1

This is my CSV file

CSV file with description

I am trying to read the data however, instead of showing as four columns, it reds as 6 individual columns. The commas are the issue but I cant figure out how to parse the data properly. Could someone help me figure this out?

Code:

using(StreamReader sr = new StreamReader(file, true)) {
  sr.ReadLine();
  while ((line = sr.ReadLine()) != null) {
    if (line.Contains("\"")) {
      line = String.Format("\"{0}\"", line.Replace("\"", "\"\""));
    }
    data = line.Split(delims, StringSplitOptions.None);
    username = data[0].ToString().Trim();
    profile = data[1].ToString().Trim();
    string[] marketvalues = data[2].ToString().Split(',');
    default_market = data[3].ToString().Trim();
  }
}

Raw CSV

Username,Profile,Markets,Default Market
kw044352,,"Kitts,Test,Vincent",
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Walters
  • 119
  • 16
  • 2
    Your CSV file doesn't have a grid in it. This is just how it is rendered in Excel or other spreadsheet programs. Please show the actual text of the CSV file. – Code-Apprentice Oct 10 '19 at 16:16
  • 2
    Why not use a CSV parsing library? there's plenty of them on nuget – vc 74 Oct 10 '19 at 16:17
  • 1
    best to look at a CSV parse like filehelper – Kevin Oct 10 '19 at 16:17
  • 1
    Instead of reinventing the wheel go and find a NuGet package that does all this for you. There are plenty of good and tested ones out there. – Igor Oct 10 '19 at 16:17
  • You need a proper csv parser which will account for escaped seperators. – Mat J Oct 10 '19 at 16:18
  • Could you guys give me some ideas of some packages? – Walters Oct 10 '19 at 16:18
  • 1
    CsvHelper: https://www.nuget.org/packages/CsvHelper/ – mxmissile Oct 10 '19 at 16:18
  • I also like https://www.nuget.org/packages/TinyCsvParser/ – Kevin Oct 10 '19 at 16:20
  • [TextFieldParser](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser?view=netframework-4.8) is already a part of the framework. – Kenneth K. Oct 10 '19 at 16:22
  • I'd recommend using the TextFieldParser. NuGet packages are nice, but make sure they match the .Net framework you are on. I tend to not use NuGet packages as much as it's extra technical debt you have to maintain, and if the package isn't updated for the newer .Net frameworks you might run into problems down the road when you move onto .Net Core. – JohnPete22 Oct 10 '19 at 16:42

0 Answers0