Problem with streamreader - C #

0

I'm practicing with streamreader in C # and I had the following problem

 System.IO.StreamReader sr = new System.IO.StreamReader(@"c:\vertices.txt");
        {
            string line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {

                if ((line[0].ToString()!="#")&(string.IsNullOrWhiteSpace(line)==false))
                {

                        cont = cont + 1;
                        Console.WriteLine(line);

                }
            }
        }

In the line of the IF I throw an error out range in line [0] .tostring I do not understand why being the first character has a value in this case '#' and in fact this problem is fixed when I nest the conditions in two IF does not throw the error index out range the problem is that nose because it can not be in a single IF and why it throws the error index out range.

    
asked by Shiki 24.01.2018 в 23:37
source

1 answer

3

There are two problems in your condition:

On the one hand you should use the operator && instead of & . First you should check that the line is not empty and, if so, check that the first character is not # . The operator & always evaluates the two expressions, the operator && only evaluates the second one if the first one is true.

On the other hand, the order should be the reverse: first check that the line is not empty and second that the first character is not the one searched for.

Something like this:

if (!string.IsNullOrWhiteSpace(line) && line[0].ToString()!="#")
    
answered by 24.01.2018 / 23:52
source