Even though you are using C#, there is a very useful class called TextFieldParser
in the Microsoft.VisualBasic namespace. You will need to add a reference to your project in addition to the using
directive:
using Microsoft.VisualBasic.FileIO;
Then you can implement something similar to as follows:
private void Parse()
{
using (TextFieldParser parser = new TextFieldParser("file.csv")
{
HasFieldsEnclosedInQuotes = true,
Delimiters = new string[] {
","
}
})
{
string[] fields;
do
{
fields = parser.ReadFields();
PrintResults(fields);
}
while (fields != null);
}
}
private void PrintResults(string[] fields)
{
if (fields != null)
{
foreach (var field in fields)
{
Console.Write(string.Concat("[", field, "] "));
}
Console.WriteLine();
}
}
The HasFieldsEnclosedInQuotes = true
property of the TextFieldParser
in your case must be set to achieve desired behavior.
I have placed your CSV sample data into a file and run as a test. The data I started out with was (in a local file named "file.csv"):
ID,Name,Address,PhoneNumber
101,Jack,"No 13, HillTop, London",012346789
102,Harry,"No 15, Baker Street London",012346789
And the resultant output in the console from calling the above Parse()
method is:
[ID] [Name] [Address] [PhoneNumber]
[101] [Jack] [No 13, HillTop, London] [012346789]
[102] [Harry] [No 15, Baker Street London] [012346789]