Search code examples
c#csvcsvreader

I am trying to confirm that this program is working properly, is there a way to output the values of these arrays to the console?


I am trying to confirm that this program is working properly, is there a way to output the values of these arrays to the console?

using System;
using Microsoft.VisualBasic.FileIO;

class ReadingCSV
{
    public static void Main()
    {
        string column1;
        string column2;
        var path = @"I:\Mfg\Process Engineering\User mfg\Tyler Gallop\CSV Reader\excel_test.csv";
        using (TextFieldParser csvReader = new TextFieldParser(path))
        {
            csvReader.CommentTokens = new string[] { "#" };
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;

            // Skip the row with the column names
            csvReader.ReadLine();

            while (!csvReader.EndOfData)
            {
                // Read current line fields, pointer moves to the next line.
                string[] fields = csvReader.ReadFields();
                column1 = fields[0];
                column2 = fields[1];
            }
        }
    }
}

Solution

  • You can concatenate the array of strings that you got back using string.Join, and print them to the console using WriteLine().

    System.Console.WriteLine(string.Join(',', fields);
    

    If you want to print the items of the array individually, then just loop over them calling WriteLine... some variation of the below:

    Console.WriteLine("Here's some fields in a line");
    foreach(var field in fields)
        Console.WriteLine(field);