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
  • No comments exist for this post.
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.