views:

661

answers:

2

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();
            }
        }
+3  A: 

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.

RichieHindle
Another option is to use a do-while loop, and make the while condition check for reader.Peek() != -1
Breakthrough
I do agree with Breakthrough, just use a foot-controlled-loop and things work out fine. Sadly, most programmers today do not care about when to use what kind of loop.
BeowulfOF
@Breakthrough, @BeowulfOF: How would your do-while loop work when given an empty file?
RichieHindle
+1  A: 

Hi there.

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.

Cheers. Jas.

Jason Evans