What I'm trying to accomplish is to read CSV file and get the count of commas in each row. ALL CSV files are identical. Have 9 columns and they are separated by (,)
So I wrote a simple function that reads the files and using foreach
loop I read each line in the file.
public static void readCSVFile(string path)
{
string _path = path;
string [] text = File.ReadAllLines(_path);
foreach (string line in text)
{
string currentLine = line;
Console.WriteLine("\t" + line);
}
}
So typically currentLine
will have an output like this:
number , 10/21/14 07:01:10, 00:28:29, number (name), number; number (name), number, number (name), N/A, number
There're total of eight ,
in the line. How can I programmatically get the total number of commas
in each line, so I can do something like this in my foreach
loop:
foreach (string line in text)
{
string currentLine = line;
if (totalNumberOfCommas == 8)
{
//do something
}
else
{
//do something else
}
You could try something like this
One way would be to use the String.Split functionality.
Note that this will not work properly if you have commas in your actual data (not as a field separator). You should probably look into a csv parser to help with this sort of thing.
If you just want to count the commas, you can take advantage of the fact that string implements
IEnumerable<char>
, so you can useCount
like this: