流读取器中的空引用
你好,我有这段代码,它运行良好:
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 个目标作为注释),一切正常。请指教
hello i had this code and it worked well:
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;
}
}
}
}
It was perfect and i got all the 4 checkbox checked when i got the correct text in the file.
However, I am receiving Nullreference error over at this line:
if (sr.ReadLine().StartsWith("Exec_text"))
{
ExectextCheckBox.IsChecked = true;
}
When test it out for 1 target(means i make the other 3 targets as comments), it all worked fine. Please advice
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过评估每个 if 语句,正在读取一行。更好的方法是阅读该行,然后使用多个 if:
With the evaluation of EACH if statement a line is being read. Better is to read the line and then have the multiple ifs:
Geremychan,在您发布的代码中,对于每次迭代,您都会检查一次
Peek()>=0
并在其后读取四行!检查一次
Peek()>=0
只能保证其后有一行。修改您的代码如下:
Geremychan, in the code you have posted, for each iteration you are checking the
Peek()>=0
once and reading four lines after it !Checking
Peek()>=0
once only gurantees that there is one line after it.Modify your code as below:
如果您的流不再有任何行可读取,Readline() 返回 null。所以你应该检查 null 或考虑使用
而不是 while(sr.Peek()>=0)
Readline() return null if your stream did not have any line to read anymore. so you should check for null or think about using
instead of while(sr.Peek()>=0)