c# - streamreader 中的空引用

标签 c# wpf streamreader

你好,我有这段代码,它运行良好:

    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 个复选框。

但是,我在这一行收到空引用错误:

if (sr.ReadLine().StartsWith("Exec_text"))
{
      ExectextCheckBox.IsChecked = true;
}

当针对 1 个目标(意味着我将其他 3 个目标作为注释)进行测试时,一切正常。请指教

最佳答案

通过评估 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/

相关文章:

c# - 如何将特定的 Json 节点反序列化为 Dictionary<string,object>?

c# - 如何在异常堆栈中定位特定异常

c# - 如何在WPF中基于索引动态生成Togglebutton并对其执行操作

c# - 如何删除 WPF 4.5 Datagrid 中的几个不需要的列?

c# - 并行读取一个非常大的文件 C#

c# - TreeView 和 Entity Framework 绑定(bind)

c# - 为什么 Contains() 返回 false 但包装在列表中而 Intersect() 返回 true?

c# - WPF 样式并未应用于所有预期的控件

c# - 对于大文件,StreamReader非常慢

c# - 搜索 FileStream 然后使用 StreamReader 从那里读取