The following PopulateCsvIntoArray method used to read the CSV file
into a two-dimensional array of strings.
I have included explanation of
method lines, wherever needed.
/// <summary>
/// Populate the CSV file into
an array,
/// We assume that every line has the
same number of fields and there may be blank lines.
/// </summary>
/// <returns></returns>
private string[,]
PopulateCsvIntoArray()
{
// Get path of CSV file.
var path = Server.MapPath("~/Folder_Name/testfile.csv");
// Get the file's text using ReadAllText method.
string fileData =
System.IO.File.ReadAllText(path);
// Split CSV data into lines.
fileData =
fileData.Replace('\n', '\r');
string[] lines =
fileData.Split(new char[] { '\r' },
StringSplitOptions.RemoveEmptyEntries);
// Get rows and columns counts.
int totalRows = lines.Length;
int totalCols =
lines[0].Split(',').Length;
// Allocate the data array.
string[,] resultVals = new string[totalRows,
totalCols];
// Populate the array by looping through rows and
columns.
for (int row = 0; row <
totalRows; row++)
{
string[] line_r =
lines[row].Split(',');
for (int col = 0; col < totalCols; col++)
{
resultVals[row, col] = line_r[col];
}
}
// Return the output result.
return resultVals;
}
|
Comments
Post a Comment