C#Null引用异常和StreamReader

时间:2016-02-27 23:04:52

标签: c# windows-forms-designer

从txt文件中读取数据时,我得到空引用异常。

     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继承自Appointments。文件存在,文件位置正确。有趣的是程序在30分钟前工作我只是从下面改变了Load方法,你可以在上面看到:

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

现在它在两种情况下都不起作用。

1 个答案:

答案 0 :(得分:3)

您的代码在每个循环中读取两次。这意味着,如果在读取文件的最后一行时文件的行数为奇数,则在while语句中对null进行检查可使代码进入循环,但后面的ReadLine返回空字符串。当然,尝试读取空字符串的索引零处的char将抛出NRE异常。

您的文件中还存在空行问题。如果存在空行,则再次读取索引零将使索引超出范围异常

您可以通过这种方式修复代码

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