Reputation: 59
I'm trying to read an csv file with the format: name, location Joseph, "street xpto, London"
When I read CSV, I split the file to ",", but when the line has "street xpto, London" (other commas) it doesn't work.
Is there some solution to that? I need to do split ignoring commas when find an " ".
var reader = new StreamReader(File.OpenRead(@"C:\example_File.csv"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
String[] values = line.Split(',');
for (int i = 0; i < values.Length; i++)
{
}
}
Upvotes: 1
Views: 3906
Reputation: 6963
Don't reinvent the wheel. There are extremely good libraries that will help you do all this. The one I like is CsvHelper
available through nuget
Install-Package CsvHelper
or from the project home page.
Upvotes: 4
Reputation: 716
Text field parser handles this already
using System;
using Microsoft.VisualBasic.FileIO;
class Program
{
static void Main()
{
using (TextFieldParser parser = new TextFieldParser("C:\\csv.txt"))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] parts = parser.ReadFields();
if (parts == null)
{
break;
}
Console.WriteLine("{0} field(s)", parts.Length);
}
}
}
}
Upvotes: 0