Hi you all,
I have the following code to put a CSV file into a DataTable.
// read CSV file
private DataTable BuildDataTable(string fileFullPath, char seperator)
{
const int EOF = -1;
DataTable myTable = new DataTable("MyTable");
DataRow myRow;
try
{
StreamReader myReader = new StreamReader(fileFullPath);
}
catch (Exception ex)
{
MessageBox.Show("Error opening streamreader: " + ex.Message);
return new DataTable("Empty");
}
try
// Open file and read first line to determine how many fields there are.
{
string[] fieldValues = myReader.ReadLine().Split(new Char [] {seperator,';'});
// Adding the first line of data to data table (columnnames?
// Create data columns accordingly
for (int i = 0; i < fieldValues.Length; i++)
{
myTable.Columns.Add(new DataColumn(fieldValues[i].ToString().Trim()));
}
//Now reading the rest of the data to data table
while (myReader.Peek() != EOF)
{
fieldValues = myReader.ReadLine().Split(new Char [] {seperator});
myRow = myTable.NewRow();
for (int i = 0; i < fieldValues.Length; i++)
{
myRow[i] = fieldValues[i].ToString().Trim();
}
myTable.Rows.Add(myRow);
}
}
catch (Exception ex)
{
MessageBox.Show("Error building datatable: " + ex.Message);
return new DataTable("Empty");
}
finally
{
if (myReader != null)
{
myReader.Close();
}
}
myTable.AcceptChanges();
return myTable;
}
It actually works fine, except for line 10, I get an error if the same file is already open by another application.
So I though I would throw in another try catch block.
But then I get 5 errors that "The name 'myReader' does not exist in the current context"
What am I doing wrong here?
Any help, as always much appreciated :)