How to read a .CSV file using C# (.NET)

.CSV are a popular way of exporting predominantly spreadsheet style information from one source to another. Reading a .CSV file correctly isn't just a case of simply using the split command because some "cells" (for want of a better word) in the line might contain a comma and you want those cell to be complete and not spread across two items in a list or array. The code below in C# shows you one way of doing it. You pass in a line and it returns a collection of "cells"."

    static List SplitCSVLine(string Line)
    {
        string sWord = "";
        List oListReturn = new List();
        string[] sParts = Line.Split(',');
        for (int i = 0; i < sParts.Length; i++)
        {
            if (sParts[i].StartsWith("\""))
            {
                sWord = "";
                while (i < sParts[i].Length)
                {
                    if (sWord != "") sWord += ",";
                    sWord += sParts[i];
                    if (sParts[i][sParts[i].Length - 1] == '\"')
                    break;
                    i++;
                }
                sWord = sWord.Substring(1, sWord.Length - 2);
                while (sWord.Contains("\"\""))
                    sWord = sWord.Replace("\"\"", "\"");
            }
            else
                sWord = sParts[i];
            oListReturn.Add(sWord);
        }
        return oListReturn;
    }

What you would do is to pass a line into the function and a generic list collection is returned. Its not by all means perfect, if the import data had a cell with multiple quotes, they'd be stripped out. Why a cell would have multiple speech marks at the end or beginning is anyones guess.

You can use the following main function to test out the code.

    static void Main(string[] args)
    {
        StreamReader oFS = new StreamReader("C:\\temp\\test.csv");
        List oLine = null;
        string sLine = "";
        while (oFS.EndOfStream == false)
        {
            sLine = oFS.ReadLine();
            oLine = SplitCSVLine(sLine);
            if (sLine != "")
            {
                Console.WriteLine(sLine + " - " + oLine.Count.ToString());
                foreach (string sWord in oLine)
                {
                    Console.WriteLine("\t" + sWord);
                }
            }
        }
        oFS.Close();
        Console.ReadKey();
    }


Here's some test data to use to test the functionality.


345,"Test Message, Ok", 34
3534,Test, Message, Ok, 45
434,"Test, Message, Ok", 4
3,"Test Message"," Ok", 44
"""Magic Number"""
"""Magic, Number""",4434,"Fantastic"

Tags - .NET   File

Last Modified : June 2023


About... / Contact.. / Cookie...