2

I am trying to write 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 specifically as it is part of design. Thanks ahead of time!

3
  • Look at CSVHelper if you need to parse into entities. Its on Nuget or here : github.com/JoshClose/CsvHelper
    – StuartLC
    Aug 24, 2012 at 3:41
  • @SimonWhitehead This is what my csv looks like. I want to pull each line in to an an array that has 1 (the atomic number) and 1.007.... (the atmoic mass) all separately callable. Im trying to put together a periodic table of sorts. 1,1.0079400000,Hydrogen,H 2,4.0026020000,Helium,He 3,6.9410000000,Lithium,Li 4,9.0121820000,Beryllium,Be
    – rreichel
    Aug 24, 2012 at 13:07
  • New lines occur after each atomic symbol.
    – rreichel
    Aug 24, 2012 at 13:12

3 Answers 3

6

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:

Column1,Column2,Column3,Column4
Row1Value1,Row1Value2,Row1Value3,Row1Value4
Row2Value1,Row2Value2,Row2Value3,Row2Value4
Row3Value1,Row3Value2,Row3Value3,Row3Value4
Row4Value1,Row4Value2,Row4Value3,Row4Value4
Row5Value1,Row5Value2,Row5Value3,Row5Value4

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.

4
  • This is what my csv looks like. I want to pull each line in to an an array that has 1 (the atomic number) and 1.007.... (the atmoic mass) all separately callable. Im trying to put together a periodic table of sorts. 1,1.0079400000,Hydrogen,H 2,4.0026020000,Helium,He 3,6.9410000000,Lithium,Li 4,9.0121820000,Beryllium,Be
    – rreichel
    Aug 24, 2012 at 13:11
  • There is a new line started after each atomic symbol.
    – rreichel
    Aug 24, 2012 at 13:12
  • Alright, I just attempted to implement your block of code and it didn't give me any errors, however I am not able to call the array list name (oCsvList) from outside of the reading (specifically trying to call it from a for loop.
    – rreichel
    Aug 24, 2012 at 13:57
  • Howdy, I'm not sure what you mean - is it possible to paste your code here please?
    – Rastus7
    Aug 28, 2012 at 23:46
0

All you need to do is simply convert it into a byte[] array and back into a string[builder?]. Then seperate each entry, and parse it like so.

http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Convert-file-to-byte-array.html

And to convert to a string:

    // C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);

You have to understand you need to make a parser. I made one to pull in Yahoo Stocks, basically splitting the colons into data.

0

This is a much simpler way to do what you want.

var lineCount = File.ReadLines(@"C:\file.txt").Count();
var reader = new StreamReader(File.OpenRead(@"C:\location1.csv"));
int[,] properties = new int[lineCount,4];
for(int i2 = 0; i2 < 4; i2++)
{
    for(int i = 0; i < lineCount; i++)
    {
        var line = reader.ReadLine();
        var values = line.Split(';');
        properties[i,i2] = Convert.ToInt32(values[i2];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.