开发者

null reference in streamreader

开发者 https://www.devze.com 2023-02-17 06:38 出处:网络
hello i had this code and it worked well: private vo开发者_JAVA百科id Textparsing() { using (StreamReader sr = new StreamReader(Masterbuildpropertiespath))

hello i had this code and it worked well:

    private vo开发者_JAVA百科id 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


With the evaluation of EACH if statement a line is being read. Better is to read the line and then have the multiple ifs:

var line = reader.ReadLine();
if(!String.IsNullOrEmpty(line)
{
    if(line.StartsWith(...))
    { ... }
    if(line.StartsWith(...))
    { ... }
}


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:

        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; 
                } 
             .......
          }


Readline() return null if your stream did not have any line to read anymore. so you should check for null or think about using

while(sr.ReadLine())
{
}

instead of while(sr.Peek()>=0)

0

精彩评论

暂无评论...
验证码 换一张
取 消