1

I am having a problem in searching a substring from a string.

StreamReader objReader = new StreamReader("D:\\C#\\Mid\\project\\real estate\\store.txt");
string sLine = "";
ArrayList arrText = new ArrayList();
Console.Write("Type the keyword you want to search : ");
string search = Console.ReadLine();

while (sLine != null)
{
    sLine = objReader.ReadLine();
    int x = sLine.IndexOf(search);
    Console.WriteLine(x);
    if (sLine != null && x != -1)
    {
        Console.WriteLine(x);
        arrText.Add(sLine);
     }
     Console.WriteLine(x);
}
Console.WriteLine("Here");
objReader.Close();

foreach (string sOutput in arrText)
    Console.WriteLine(sOutput);
Console.ReadLine();

The message i am getting is

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

1
  • 3
    Check whether sLine is null before sLine.IndexOf(search); Commented Sep 26, 2013 at 18:04

3 Answers 3

1
sLine = objReader.ReadLine();

You need to check to see if sLine is null, as ReadLine() will return NULL if there wasn't anything to read.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to add !objReader.EndOfStream in your loop condition

while (sLine != null && !objReader.EndOfStream)
{
.
.
.
}

Comments

0

Your loop is incorrect because sLine would not obtain a null value until objReader.ReadLine() is called. Instead you should change your loop to the following:

using(StreamReader objReader = new StreamReader("file_location"))
{
    do
    {
        sLine = objReader.ReadLine();

        if(sLine != null)
        //do stuff
     }
     while(!objReader.EndOfStream);

 }

I don't use do..while loops all that often, but in this situation it may be a good idea since you need to call ReadLine() first to at least begin reading the file. This way if you are at the end of the stream it will return NULL and skip your if block and then break since it'll be at the end of the stream when it hits the post-condition.

In addition, I know this is just a basic example, but make sure you add in error handling code since most of these statements can throw exceptions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.