Prabhu
Prabhu

Reputation: 13355

StreamReader.EndOfStream missing last line?

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();
            }
        }

Upvotes: 2

Views: 15739

Answers (2)

Jason Evans
Jason Evans

Reputation: 29186

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.

Upvotes: 5

RichieHindle
RichieHindle

Reputation: 281805

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.

Upvotes: 11

Related Questions