locked
.csv to 2D array RRS feed

  • Question

  • Hi all. I know this has been asked before, because I have read numerous threads on this site and other websites, but they either have errors in the code or are really old answers. How can I read a .csv file using fileIO or filestream or similar, write it to a 2D array, and then access the data for further processing? Thank you, Ron
    Monday, July 7, 2014 8:13 PM

Answers

  • The code below should work.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\abc.csv";
            static void Main(string[] args)
            {
                
                List<List<string>> d2array = new List<List<string>>();
                string inputLine = "";
    
                StreamReader reader = new StreamReader(FILENAME);
    
                while ((inputLine = reader.ReadLine()) != null)
                {
                    List<string> inputArray = inputLine.Split(new char[] { ',' }).ToList();
                    //remove extra spaces
                    inputArray = inputArray.Select(x => x.Trim()).ToList();
                    d2array.Add(inputArray);
                }
    
            }
        }
    }
    

    Monday, July 7, 2014 9:30 PM