I can save to a text file, so why do I need to save to a CSV file?

If you are saving small amounts of text a text file is just fine. However, you can't do much to organise your data. CSV files allow you to organise your data into columns.

CSV stands for Comma Separated Values

Data in a CSV file is separated by commas. For example let's save Mary and Jeremy's full names and ages. Here is the data shown in notepad.

text

Viewing in Microsoft Excel

If you open the same file in Microsoft Excel the data will be separated into columns using the comma as a delimiter (separator).

text

Add the required library

Add the top of the form type the code:

using System.IO;

text

Saving data to a CSV file.

The code below shows you have this data was saved. Note the file is saved with extension .csv instead of .txt.

using (StreamWriter writer = new StreamWriter("NewNames.csv"))
{
    writer.WriteLine("Mary, Young, 14");
    writer.WriteLine("Jeremy, Hicks, 12");
}

Retrieving data from a CSV file.

You can retrieve data from a CSV file in almost the exact same way as you would from a text file. Every time you read one line of data you just need to split the data up using the delimiter.

using (StreamReader r = new StreamReader("NewNames.csv"))
{
    while (r.Peek() != -1)
    {
        String row = r.ReadLine();

        // split the row by the delimiter
        string[] parts = row.Split(',');

        // show each piece of text from the row
        foreach (string s in parts)
        {
            MessageBox.Show(s);
        }
    }
}