你好,我有这段代码,它运行良好:
private void Textparsing()
{
using (StreamReader sr = new StreamReader(Masterbuildpropertiespath))
{
while (sr.Peek() >= 0)
{
if (sr.ReadLine().StartsWith("Exec_mail"))
{
ExecmailCheckBox.IsChecked = true;
}
if (sr.ReadLine().StartsWith("Exec_text"))
{
ExectextCheckBox.IsChecked = true;
}
if (sr.ReadLine().StartsWith("Exec_3"))
{
Exec3CheckBox.IsChecked = true;
}
if (sr.ReadLine().StartsWith("Exec_4"))
{
Exec4CheckBox.IsChecked = true;
}
}
}
}
这是完美的,当我在文件中得到正确的文本时,我选中了所有4个复选框。
但是,我在此行收到Nullreference错误:
if (sr.ReadLine().StartsWith("Exec_text"))
{
ExectextCheckBox.IsChecked = true;
}
当测试一个目标(意味着我将其他三个目标作为注释)时,一切正常。请指教
最佳答案
通过对EACH if语句的评估,正在读取一行。更好的方法是阅读该行,然后具有多个ifs:
var line = reader.ReadLine();
if(!String.IsNullOrEmpty(line)
{
if(line.StartsWith(...))
{ ... }
if(line.StartsWith(...))
{ ... }
}
关于c# - Streamreader中的空引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5321940/