C#空引用异常和StreamReader
从txt文件读取数据时出现空引用异常C#空引用异常和StreamReader,c#,windows-forms-designer,C#,Windows Forms Designer,从txt文件读取数据时出现空引用异常 public class Appointments : List<Appointment> { Appointment appointment; public Appointments() { } public bool Load(string fileName) {
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;
}
}
现在,这两种情况都不起作用。您的代码在每个循环中读取两次。这意味着,如果在读取文件的最后一行时文件的行数为奇数,则while语句中的null检查允许代码进入循环,但下面的ReadLine返回null字符串。当然,尝试读取空字符串的索引0处的字符将引发NRE异常 文件中还有空行的问题。如果有一个空行,那么再次读取索引0将抛出索引超出范围异常 您可以用这种方式修复代码
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;
}
}
除此之外,你还打了两次readline……为什么过了一会儿你还要读另一行?这将在最后一行终止应用程序(如果行数为奇数)。事实上,最后一行将从while中读取,但另一个ReadLine没有要读取的内容并返回null。您是否在文件中添加了新行?我猜是坏习惯:D.删除额外任命后Data=reader.ReadLine()。我获取的索引超出范围错误。可能是您的文件中的某些内容。(当然,如果您的文件包含空行,那么读取索引[0]处的字符将抛出)请显示输入文件的一些行。这是处理文件读取的好方法:D。感谢您的输入。希望我能给您一些+rep:(。
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;
}
}