I am trying to read a text file using the code (pasted below), but the last line of the file does not get read. Is my logic correct?
using (StreamReader reader = new StreamReader(stream))
{
try
{
string line = reader.ReadLine();
string[] data = BreakLine(line);
while (!reader.EndOfStream)
{
data = BreakLine(line);
DataRow dr = _DataTable.NewRow();
// protect against overflow
int maxColumns = Math.Min(_DataTable.Columns.Count, data.Length);
for (int i = 0; i < maxColumns; i++)
{
dr[i] = data[i];
}
_DataTable.Rows.Add(dr);
line = reader.ReadLine();
}
return _DataTable;
}
finally
{
reader.Close();
reader.Dispose();
stream.Close();
}
}
Here's the problem: because you have this:
line = reader.ReadLine();
as the last line of your while loop, it will read the last line and then discard it because the while condition will return false.
I think you need this:
try
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] data = BreakLine(line);
DataRow dr = _DataTable.NewRow();
// protect against overflow
int maxColumns = Math.Min(_DataTable.Columns.Count, data.Length);
for (int i = 0; i < maxColumns; i++)
{
dr[i] = data[i];
}
_DataTable.Rows.Add(dr);
}
return _DataTable;
}
finally
{
...
So you just read each line as the first thing you do each time round the loop.
A quick tip - you don't need this in the finally block:
finally
{
reader.Close();
reader.Dispose();
Since you have a Using block for 'reader', it will automatically get disposed for you, even if there is an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With