Last line missing in StreamReader.EndOfStream?

I am trying to read a text file using the code (inserted below), but the last line of the file is unreadable. 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();
            }
        }

      

+2


source to share


2 answers


Here's the problem: because you have this:

line = reader.ReadLine();

      

as the last line of your loop while

, it will read the last line and then cancel it because the condition while

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 like the first thing you do each time in a loop.

+10


source


Quick tip - you don't need this in a finally block:

finally
{
   reader.Close();
   reader.Dispose();

      



Since you have a Usage block for the reader, it will automatically be removed for you, even if there is an exception.

+5


source







All Articles