I'm reading a text file using a stream read and my code goes like this

FileStream file = new FileStream("c:/data/theData.txt", FileMode.Open, FileAccess.Read);
StreamReader streamReader = new StreamReader(file);

// read the content of the first line of the data text file
String line = streamReader.ReadLine();

while (line != "")
{
   // check the value of the line
   if (line.Equals("<data>"))
   {
     ..... // code here
   }

    // read the next line of the text file
    line = streamReader.ReadLine();
}

the problem is that whenever i run my program, this error occurs on runtime:
"Object reference not set to an instance of an object" and it's pointing at the
"if(line.Equals("<data>"))"... what's wrong? i used to do this in java and it works..

Well first of all, C# and Java are NOT the same language. they have many similar parts, but they are not the same. Now i'm not sure why it doesnt work, but i thought i would just point that out for you.

an error... I mean line.equals(STRING).. if I remove the "" around "<data>" that it's an unknown expresson

That's not an error, it's an exception that wasn't handled. Your code threw a NullReferenceException. It basically means that some object has a null value. The problem with your code is that the file you specified (theData.txt) is empty. So, you line object is given the value of NULL, since there's nothing in the theData.txt file. the program will run if your file has some contents.

yeah i think so too that's why i placed it under a try catch block.. but the problem is that, if the exception occurs, i won't be able to close the file and i wont be able to write back into the file if i wont close the File

I'm sorry, I'm kind of lost there. What file and why aren't you able to close it?

This question has already been answered. Start a new discussion instead.