0

I am simply practicing in C#. I am mostly used to Java but I have been unable to figure out how to read a .CSV file , store it and the print out it's contents into the console. This is what I have so far. What am I doing wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = "C:\\Desktop\\csvTestFilePractice\\";
            String file1 = "testFile1.csv";
            ArrayList arryList1 = new ArrayList();
            String[] dataArray1;

            TextFieldParser CSVFile1 = new TextFieldParser(path + file1);
            CSVFile1.SetDelimiters(",");
            dataArray1 = CSVFile1.ReadFields();

            int count = 0;
            while (!CSVFile1.EndOfData)
            {
                dataArray1 = CSVFile1.ReadFields();
                Console.WriteLine(dataArray1);
            }
            Console.Read();
        }
    }
}

Also this is the file I am testing with.

______Excel View

ID  Name    Phone          State
1   Colt    864-367-8399    SC
2   Terry   864-367-8400    GA
3   Joe     864-367-8401    FL
4   Mark    864-367-8402    NC
5   Ashley  864-367-8403    CO

____Notepad View

ID,Name,Phone,State
1,Colt,864-367-8399,SC
2,Terry,864-367-8400,GA
3,Joe,864-367-8401,FL
4,Mark,864-367-8402,NC
5,Ashley,864-367-8403,CO

Thank you for any advice

Ashton
  • 363
  • 1
  • 4
  • 21
  • 1
    You have this line: `CSVFile1.SetDelimiters(",")` but your file does not appear to be delimited with commas. – Chris Dunaway May 19 '16 at 18:26
  • @ChrisDunaway I apologize it is a CSV file but I used excel to pull up the data. I will post the notepad data instead – Ashton May 19 '16 at 18:27
  • How do you want to print it? The code you posted seems OK except for the `WriteLine` statement. You could try `Console.WriteLine(string.Join(",", dataArray1));` or if you need to print in a columnar format try `Console.WriteLine("{0,2} {1,-10} {2,-14} {3, -5}", dataArray1[0], dataArray1[1], dataArray1[2], dataArray1[3]);` – Chris Dunaway May 19 '16 at 18:37
  • 1
    Possible duplicate of [Reading CSV file and storing values into an array](http://stackoverflow.com/questions/5282999/reading-csv-file-and-storing-values-into-an-array) – Andersnk May 19 '16 at 18:45
  • @Andersnk That post does not answer my specific question. I am having an issue specific to my code i've posted. – Ashton May 19 '16 at 18:48
  • @ChrisDunaway I want it to print out in a loop until the data is at the end. It just prints out `System.String[]` everytime time though in the console – Ashton May 19 '16 at 18:49
  • @ChrisDunaway is there a way to put your second example into a loop? This may be what I am trying to do – Ashton May 19 '16 at 18:55
  • Just replace your Console.WriteLine in your code with that one. It should work. I just tested your code and replaced the `Console.WriteLine` line with the one I suggested and it worked. – Chris Dunaway May 19 '16 at 19:04
  • @ChrisDunaway but if I have more then just 5 rows/columns how would I place that into a loop to do it for me without having to type out each location in the arraylist? Thank you for your help! – Ashton May 19 '16 at 19:11
  • See my answer. I used the length of the largest piece of data in each column to create the format string. – Chris Dunaway May 19 '16 at 19:30

2 Answers2

2

You shouldn't be using ArrayList anyway as it is a non-generic collection type. You should be considering how to parse the CSV into a List to avoid having to box/unbox your objects.

  • So is it impossible to do what I am trying to do with the ArrayLists? – Ashton May 19 '16 at 18:23
  • 1
    No. However `ArrayList` should NOT be used in new code. Use `List` instead. `List` corresponds to `ArrayList` in Java. See more here: http://stackoverflow.com/questions/391088/arraylist-vs-listobject – Andersnk May 19 '16 at 18:41
1

Based on questions in the comments here is a short version of the program that uses the max length of each column to create the format string. It should work with almost any csv file. I'm sure it could be improved. All columns are left justified.

void Main()
{
    List<string[]> lines = new List<string[]>();

    TextFieldParser CSVFile1 = new TextFieldParser(@"g:\test\test.csv");
    CSVFile1.SetDelimiters(",");

    //Loop through the data and create a list.  Each entry in the list
    //is a string array.  This method may be impractical for very large 
    //files.
    while (!CSVFile1.EndOfData)
    {
        lines.Add(CSVFile1.ReadFields());
    }

    //Create a format string using the length of the longest string in each column
    string formatString = createFormatString(lines);

    //Loop through all the lines and write them to the console.
    foreach (var csvLine in lines)
    {
        Console.WriteLine(formatString, csvLine);
    }
}

//Create a format string based on the number of columns and the maximum
// size of each column
private string createFormatString(List<string[]> lines)
{
    var sb = new StringBuilder();

    //Use the first array to get the number of columns.  They should all be the same
    int numberOfColumns = lines[0].Length;

    //Loop through the number of columns and find the max length and append to the format string
    for (int i = 0; i < numberOfColumns; i++)
    {
        int maxColumnWidth = lines.Select(l => l[i].Length).Max();
        sb.AppendFormat("{{{0}, -{1}}}  ", i, maxColumnWidth);
    }

    return sb.ToString();
}
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
  • I got an error with `string formatString = creatFormatString(lines);` it says an object reference is required for the non-static field, method, or property 'Program.createFormatString(List)' – Ashton May 19 '16 at 19:36
  • I coded this in LinqPad. Make sure to add the `static` keyword to the method if you're running from a regular C# console application: `private static string createFormatString(...)` – Chris Dunaway May 19 '16 at 19:41
  • That was the issue. Thank you chris for not just posting an answer but for sticking to my original problem and for explaining with comments in your code! – Ashton May 19 '16 at 19:45