【问题标题】:Getting exception when reading two lines of data from text file in C#从 C# 中的文本文件中读取两行数据时出现异常
【发布时间】:2018-12-06 16:05:09
【问题描述】:

您好,我正在从 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);
}

在文件末尾,是异常的地方。

提前感谢您的帮助。

【问题讨论】:

  • 如果 file.ReadLine() 没有返回任何东西,当你调用 Trim() 时你会得到一个 NullReferenceException(你得到的那个)
  • 两件事: 1. 努力格式化你的代码。如果人们能够阅读您的代码,他们将更愿意提供帮助。 2. 确保您提供的代码可以编译。您在无法编译的代码中有许多错误。例如:使用sting 而不是stringconsole.write 应大写:Console.Write

标签: c# file-read


【解决方案1】:

问题是代码在检查结果是否为空之前对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()

【讨论】:

    【解决方案2】:

    使用 ?。运算符,例如:

    file.ReadLine()?.Trim()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多