Arth Arth - 9 days ago 6
C# Question

C# Null reference exception and StreamReader

I am getting null reference exception when reading data from my txt file.

public class Appointments : List<Appointment>
{
Appointment appointment;

public Appointments()
{

}

public bool Load(string fileName)
{
string appointmentData = string.Empty;
using (StreamReader reader = new StreamReader(fileName))
{
while((appointmentData = reader.ReadLine()) != null)
{
appointmentData = reader.ReadLine();
//**this is where null ref. exception is thrown** (line below)
if(appointmentData[0] == 'R')
{
appointment = new RecurringAppointment(appointmentData);
}
else
{
appointment = new Appointment(appointmentData);
}
this.Add(appointment);
}
return true;
}
}


RecurringAppointment
inherits from
Appointments
. File exists, file location is correct. Funny thing is that program was working 30 min ago I've only changed Load method from below to what u can see above :

public bool Load(string fileName)
{
string appointmentData = string.Empty;
using (StreamReader reader = new StreamReader(fileName))
{
while((appointmentData = reader.ReadLine()) != null)
{
appointmentData = reader.ReadLine();
if(appointmentData[0] == 'R')
{
this.Add(appointment = new RecurringAppointment(appointmentData));
}
else
{
this.Add(appointment = new Appointment(appointmentData));
}
}
return true;
}
}


Now it does not work in either case.

Answer

Your code reads two times at each loop. This means that, if your file has an odd number of rows when you read the last line of the file, the check against null inside the while statement allows your code to enter the loop but the following ReadLine returns a null string. Of course trying to read the char at index zero of a null string will throw the NRE exception.

There is also the problem of empty lines in your file. If there is an empty line then, again reading at index zero will throw an Index out of range exception

You could fix your code in this way

public bool Load(string fileName)
{
    string appointmentData = string.Empty;
    using (StreamReader reader = new StreamReader(fileName))
    {
        while((appointmentData = reader.ReadLine()) != null)
        {
            if(!string.IsNullOrWhiteSpace(appointmentData))
            {
                if(appointmentData[0] == 'R')
                    this.Add(appointment = new RecurringAppointment(appointmentData));
                else
                    this.Add(appointment = new Appointment(appointmentData));
            }
        }
        return true;
    }
}