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

Recommended Answers

All 9 Replies

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.

try to remove the "" around "<data>". Tell us what you see then...

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?

ithink you lost file share with declare the file

Change:
("c:/data/theData.txt",
TO
("c:\\data\\theData.txt",

and try it again.

// Jery

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.