3

How can i read a CSV file into a multidimensional array?

public void CSV_ToArray(string filePath)
    {
        try
        {
            StreamReader sr = new StreamReader(filePath);
            int colCount = 3;
            int rowCount = getNumberOfRows(sr);

            string[,] Contacts = new string[rowCount, colCount];
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }

    }

I've already created the array with it's dimensions but unsure as to how to assign the data to each position in the array

The format of the CSV file will be firstName, LastName, Email

Graham Warrender
  • 365
  • 1
  • 8
  • 20
  • Use the proper tool. Check out `Microsoft.VisualBasic.FileIO.TextFieldParser` – Sam Axe Feb 25 '15 at 23:04
  • I would rather [read it into a DataTable](http://stackoverflow.com/questions/1050112/how-to-read-a-csv-file-into-a-net-datatable). – Uwe Keim Feb 25 '15 at 23:07

2 Answers2

3

The comments explain that it might be better to use a predefined library, and perhaps parse into a DataTable.

If you do not mind a jagged array instead of a two-dimensional array, consider the following one-liner:

string[][] lines = File.ReadLines(path)
          .Select(s => s.Split(",".ToCharArray())).ToArray().ToArray();

You can access it using lines[1][3] instead of lines[1,3]

In your case, perhaps it would be even better to create a class for it:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }

    public Contact(string firstName, string lastName, string emailAddress)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.EmailAddress = emailAddress;
    }

    public static Contact[] LoadContacts(string csvFile)
    {
        return File.ReadLines(csvFile).Select(CreateFromCsvLine).ToArray();
    }
    private static readonly char[] separator = new[] { ',' };
    private static Contact CreateFromCsvLine(string line)
    {
        string[] split = line.Split(separator);
        return new Contact(split[0], split[1], split[2]);
    }
}

In that case you can do:

Contact[] contacts = Contact.LoadContacts("contacts.csv");
string name = contacts[0].LastName;
Bas
  • 26,772
  • 8
  • 53
  • 86
3

You could add a method which recivies a path and a separator and prepare it to return a string[][]. For sample:

using System.IO;

public static string[][] CSV_ToArray(string path, string separator = ";")
{
    // check if the file exists
    if (!File.Exists(path))
        throw new FileNotFoundException("The CSV specified was not found.");

    // temporary list to store information
    List<string[]> temp = new List<string[]>();

    using (var reader = new StreamReader(File.OpenRead(path)))
    {
        while (!reader.EndOfStream)
        {
            // read the line
            string line = reader.ReadLine();

            // if you need to give some changes on the inforation
            // do it here!
            string[] values = line.Split(separator.ToCharArray());

            // add to the temporary list
            temp.Add(values);           
        }
    }

    // convert te list to array, which it will be a string[][]
    return temp.ToArray();  
}

and use it:

string[][] csv = CSV_ToArray("myFile.csv");

or using another separator:

string[][] csv = CSV_ToArray("myFile.csv", ",");
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194