Title: Read a CSV file into an array in C#
The following 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 split the lines into fields and adding their values to the array. When it's done, the method returns the two-dimensional array of strings.
When you click the Go button, the following code calls the LoadCsv method and displays the result in a DataGridView control.
// Read the CSV file.
// Assumes each line has the same number of fields
// and no line is blank.
private void btnGo_Click(object sender, EventArgs e)
{
// Get the data.
string[,] values = LoadCsv(txtFile.Text);
int num_rows = values.GetUpperBound(0) + 1;
int num_cols = values.GetUpperBound(1) + 1;
// Display the data to show we have it.
// Make column headers.
// For this example, we assume the first row
// contains the column names.
dgvValues.Columns.Clear();
for (int c = 0; c < num_cols; c++)
dgvValues.Columns.Add(values[0, c], values[0, c]);
// Add the data.
for (int r = 1; r < num_rows; r++)
{
dgvValues.Rows.Add();
for (int c = 0; c < num_cols; c++)
{
dgvValues.Rows[r - 1].Cells[c].Value = values[r, c];
}
}
}
This code calls LoadCsv and saves the returned strings in an array. It uses the array's GetUpperBound method twice to see how many rows and columns it contains.
Next the program clears the DataGridView control's columns. It loops through the first values in each of the array's columns and uses it to build a column in the DataGridView. For each value, it creates a column named after the value and displaying the value as its header text.
Next the code loops through the remaining rows in the table. For each row, it adds the row's values to the DataGridView control's cells.
Download the example to experiment with it and to see additional details.
|