BLOG.CSHARPHELPER.COM: Read a comma-separated value (CSV) file into an array in C#
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);
// 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.
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
Could not display the last (longitude) column. Had to modify the C< num_cols; to C<= num_cols; and r
Reply to this
Oops! The problem is in the code that displays the values. Instead of this:
Reply to this