0

Using C# program I am reading CSV File with value like (Name, Salary, Age) (A, $1,200, 27) (B, 2300, 27)

In the header row there are three columns. I want to validate that the number of columns in data rows is also three. (C, 28) should be an invalid file.

Currently I am doing this by counting the number of commas. But when the content itself is having comma ($1,200), this logic is failing. How do I solve this issue?

LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 2
    Use the right tool for the job: [A CSV parser](http://stackoverflow.com/questions/3507498/reading-csv-file/3508572#3508572) – Tim Pietzcker Sep 29 '11 at 12:24
  • Its homework or something similar? If not there are libraries you can use in commercial applications without paying. – Piotr Auguscik Sep 29 '11 at 12:27
  • What do you mean, third party? That's in the .NET BCL. Or is this perhaps a homeword assignment? – Tim Pietzcker Sep 29 '11 at 12:27
  • 2
    If the file is actually formatted like that, it isn't valid CSV. Please copy and paste an actual sample from your file in your question and format it using Ctrl-K. – Tim Pietzcker Sep 29 '11 at 12:31

3 Answers3

1

Use library for reading csv files. Why are you wrintg it on yourown when someone already did it for you?. Last time i was reading csv i used CsvHelper.

Piotr Auguscik
  • 3,651
  • 1
  • 22
  • 30
0

As a fast answer why don you split by (", ")

var s  = "Name, Salary, Age";
var t = "A, $1,200, 27";
var x = "B, 2300, 27";

string[] stringSeparators = new string[] {", "};

s.Split(stringSeparators, StringSplitOptions.None).Dump();
t.Split(stringSeparators, StringSplitOptions.None).Dump();
x.Split(stringSeparators, StringSplitOptions.None).Dump();

Not the best solution but it's one that fits....

As was commented by @Tim Pietzcker it's not a valid csv file....

Anyway....

jjchiw
  • 4,375
  • 1
  • 29
  • 30
0

Could you perhaps do this?...where fileLine would be "A, $1,200, 27". This is assuming that each column is delineated by a comma then a space.

        int lastCommaIdx = fileLine.LastIndexOf(",");
        string agePart = fileLine.Substring(lastCommaIdx + 1, fileLine.Length - (lastCommaIdx + 1)).Trim();
        int age = Convert.ToInt32(agePart);

        fileLine = fileLine.Substring(0, lastCommaIdx);
        int dollarIdx = fileLine.LastIndexOf("$");
        string salary = fileLine.Substring(dollarIdx, fileLine.Length - dollarIdx).Trim();

        string name = fileLine.Substring(0, dollarIdx).Trim().TrimEnd(new char[1] { ',' });

        Debug.WriteLine(string.Format("Name={0}, Salary={1}, Age={2}", name, salary, age));
pmcilreavy
  • 3,076
  • 2
  • 28
  • 37