1

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++)
    {
    }
}
3
  • 2
    is the address surrounded by quotations as shown? You would be better looking into a csv parsing library though.. Commented Apr 16, 2015 at 14:56
  • 3
    look here Commented Apr 16, 2015 at 15:00
  • 1
    TextFieldParseror FileHelpers are ways to go Commented Apr 16, 2015 at 15:02

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }
    }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.