Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
            }
        }
like image 230
Prabhu Avatar asked Aug 29 '26 02:08

Prabhu


2 Answers

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.

like image 193
RichieHindle Avatar answered Aug 30 '26 16:08

RichieHindle


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.

like image 28
Jason Evans Avatar answered Aug 30 '26 17:08

Jason Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!