你好,我正在用 C# 从文本文件中读取两行数据,在文件末尾出现错误“对象引用未设置为对象的实例”。我知道这个错误是因为文件结束,并且对象被分配了空值。但我需要避免这个错误。 我的代码格式如下:
try
{
sting line;
while ((line = file.ReadLine().Trim()) != null)
{
//do something
if ((line2 = file.ReadLine().Trim()) != null)
//do something
}
}
catch(exception e)
{
console.write(e.Message);
}
在文件末尾,是异常发生的地方。
提前感谢您的帮助。
最佳答案
问题是代码在检查结果是否为空之前对 ReadLine()
的结果调用 Trim()
。
来自 How to: Read a Text File One Line at a Time (Visual C#) :
while((line = file.ReadLine()) != null)
{
// Do something with line
}
另请注意,通常最好避免在循环内再次调用 ReadLine()
。
关于c# - C#从文本文件中读取两行数据时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51068216/