Read a comma-separated value (CSV) file into an array in C#

The LoadCsv method reads the CSV file into a two-dimensional array of strings.

// Load a CSV file into an array of rows and columns.
// Assume there may be blank lines but every line has
// the same number of fields.
private string[,] LoadCsv(string filename)
{
// Get the file's text.
string whole_file = System.IO.File.ReadAllText(filename);

// Split into lines.
whole_file = whole_file.Replace('\n', '\r');
string[] lines = whole_file.Split(new char[] { '\r' },
StringSplitOptions.RemoveEmptyEntries);

// See how many rows and columns there are.
int num_rows = lines.Length;
int num_cols = lines[0].Split(',').Length;

// Allocate the data array.
string[,] values = new string[num_rows, num_cols];

// Load the array.
for (int r = 0; r < num_rows; r++)
{
string[] line_r = lines[r].Split(',');
for (int c = 0; c < num_cols; c++)
{
values[r, c] = line_r[c];
}
}

// Return the values.
return values;
}

The code uses System.IO.File.ReadAllText to read the file's contents into a string. It then uses Split to break the file into lines, ignoring any blank lines.

The code then loops through the lines using Split to separate them into fields and adding their values to the array.

The main program calls LoadCsv to load the fields into an array and then displays the values in a DataGridView control. See the code for the detail about how it displays the values.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 11/14/2012 7:36 PM Michel Despatie wrote:
    Could not display the last (longitude) column. Had to modify the C< num_cols; to C<= num_cols; and r
    Reply to this
    1. 11/15/2012 2:12 PM Rod Stephens wrote:
      Oops! The problem is in the code that displays the values. Instead of this:

           int num_rows = values.GetUpperBound(0);
          int num_cols = values.GetUpperBound(1); 

      It should have used this:

           int num_rows = values.GetUpperBound(0) + 1;
          int num_cols = values.GetUpperBound(1) + 1; 

      The number of rows (and columns) in an array is 1 more than the upper bound.

      Thanks for pointing this out!
      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.