你好,我有这个代码,它运作良好:
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;
}
当测试1个目标时(意味着我将其他3个目标作为评论),一切正常。请建议
答案 0 :(得分:3)
评估EACH if语句正在读取一行。更好的是阅读该行,然后有多个ifs:
var line = reader.ReadLine();
if(!String.IsNullOrEmpty(line)
{
if(line.StartsWith(...))
{ ... }
if(line.StartsWith(...))
{ ... }
}
答案 1 :(得分:1)
Geremychan,在您发布的代码中,对于每次迭代,您检查Peek()>=0
一次,并在其后阅读四行!
检查Peek()>=0
一次只保证后面有一行。
修改您的代码如下:
using (StreamReader sr = new StreamReader(Masterbuildpropertiespath))
{
while (sr.Peek() >= 0)
{
String line=sr.ReadLine();
if (line.StartsWith("Exec_mail"))
{
ExecmailCheckBox.IsChecked = true;
}
else if (line.StartsWith("Exec_text"))
{
ExectextCheckBox.IsChecked = true;
}
.......
}
答案 2 :(得分:0)
如果您的流没有任何行可供读取,则Readline()将返回null。所以你应该检查null或考虑使用
while(sr.ReadLine())
{
}
而不是while(sr.Peek()> = 0)