rreichel rreichel - 1 year ago 113
C# Question

Read a CSV file in to an array using C#

I am trying to create a code that will pull in, read, and separate a csv file. It has four columns with no titles. I've been searching for hours online and no one really seems to have the answer so I'm hoping that someone here can. After it is read in I need it to be able to be pulled very sepecifically as it is part of design. Thanks ahead of time!

Answer Source

Your question is a little vague, but I'll try and answer it as best I can.

A CSV file is (by definition) a file containing comma seperated values - the key here is that a comma is used as the delimiter. Personally, I find that using a different delimiter is prone to less nasties when parsing.

I've created the following test CSV file:


Here's some code to read that file into some simple structures that you can then manipulate. You might want to extend this code by creating classes for the columns and rows (and values as well).

        string sFileContents = "";

        using (StreamReader oStreamReader = new StreamReader(File.OpenRead("Test.csv")))
            sFileContents = oStreamReader.ReadToEnd();

        List<string[]> oCsvList = new List<string[]>();

        string[] sFileLines = sFileContents.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        foreach (string sFileLine in sFileLines)
            oCsvList.Add(sFileLine.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));

        int iColumnNumber = 0;
        int iRowNumber = 0;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

        iColumnNumber = 4;
        iRowNumber = 2;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

Keep in mind that values are accessed by the column number, and then the row number.

I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download