Skip to main content
 首页 » 编程设计

c#之streamreader 中的空引用

2024年02月23日13birdshome

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

    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(...)) 
    { ... } 
}