How to read lines from a CSV file

ddanbe 0 Tallied Votes 3K Views Share

The test.txt file I'm using is:

1,2,3,Name1,Pizza,Pizza Hut,7,8,9
1,2,3,Name2,goose,my home,7,8,9

Most of the explanation can be found in the snippet.
Some CSV(Comma Separated Value) files often contain as first line, a header.
You could skip this, or threat it a bit differently.
I had no header, so I leave the coding of that up to you.
I made the test.txt file with Notepad, started a new windowsapplication and filled in this extra code in the Form1 constructor.

public Form1()

            const char fieldSeparator = ',';
            string filePath = @"C:\test.txt";
            using (StreamReader SR = new StreamReader(filePath))    // the way to go
                // while not end of file do
                // could also be (SR.Peek() != -1) or something like
                // ((currentLine = sr.ReadLine()) != null) :{
                while (!SR.EndOfStream) //best way to do it
                    //read a line of our file and split it into its separate values
                    var CSValues = SR.ReadLine().Split(fieldSeparator);

                    // instead of var, you could use string[] or List<string> 
                    // in the case of List<string> use the following
                    // List<string> CSValues = SR.ReadLine().Split(fieldSeparator).ToList();

                    // Now you can do anything you want with this collection of CSValues
                    // Index the list to get just the values we want and as an example, 
                    // suppose we are only interested in the 4th, 5th and 6th columnvalues:
                    // just show them in a MessageBox, separated by spaces and vertical bars
                    MessageBox.Show( CSValues[3] + " | " + CSValues[4] + " | " + CSValues[5]);
Kratoswoo 0 Newbie Poster

Here is how I did it with a .csv file and it puts the information into the textbox

private void btnSearch_Click(object sender, EventArgs e)
            string filepath = "C:***.csv";
            using (StreamReader readFile = new StreamReader(filepath))
                string line;
                while ((line = readFile.ReadLine()) != null)
                    IList<string> split = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
                    int count = 0;

                    foreach (string ln in split)
                        if (count > 4 && count < 6)
                            textBox1.Text += ("Name" + " '"+ split[6] + "','" + split[7] + "','" + "," + "," + "'" + split[5] + "'" + Environment.NewLine);

Lucaci Andrew 140 Za s|n

Here's a small Linq example:

public static IEnumerable<string[]> Read(string path)
    return from line in File.ReadLines(path)
                    select line.Split(new [] {','});
ddanbe commented: He! Nice addition. +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
  1. Read the documentation
  2. ???
  3. Profit

I've written too many CSV parsers (real ones, not this naive comma split stuff) to be interested in doing it again. ;)

ddanbe commented: Great! +15
ddanbe 2,724 Professional Procrastinator Featured Poster

He, deceptikon, thanks for sharing. Did not know this class even existed! Tell me about CVS parsing, let's say it was the main part of my professional programmining tasks, way back in the previous century.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The VisualBasic namespace has a lot of cool stuff that really shouldn't be there because it's too well hidden. FileLogTraceListener comes immediately to mind as I've been using it a lot lately.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.