-3

In my c# program, I'm reading in lines from a text file and want to check to see if the line that I read in contains the string "EHRS" and if it does, I want to put that line into an array and if not, I want to read in the next line. When I run this, I get an error that tells me that an unhandled exception of type 'System.NullReferenceException' occurred at the line where I use the contains function.

Here's what I have:

string[] concArray = new string[numLinesConcYr];

using (var sr = new StreamReader(mydocpath + @"\concYrLines.txt"))
{
    for (int i = 0; i < numLinesConcYr; i++)
    {
        concYrLine = sr.ReadLine();
        if (concYrLine.Contains("EHRS") == true)
        {
            concArray[i] = concYrLine;
        }
        else
        {
            concYrLine = sr.ReadLine();
        }
    }
}
rcarcia02
  • 927
  • 4
  • 15
  • 46

2 Answers2

2

From documentation on StreamReader.ReadLine

Return Value Type: System.String The next line from the input stream, or null if the end of the input stream is reached.

So null is expected, you have to implement defense against it.

concYrLine = sr.ReadLine();
if (!string.IsNullOrempty(concYrLine) && concYrLine.Contains("EHRS"))
{
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
0

Each time you read a line, your line my have no content. performing a .Contains("") check on the line you have read is dependent on the variable returned being an instance of a string. Perform a null check on the concYrLine proir to the .Contains() method. Like so:

for (int i = 0; i < numLinesConcYr; i++)
{
    concYrLine = sr.ReadLine();
    if (!String.IsNullOrEmpty(concYrLine) && concYrLine.Contains("EHRS") == true)
    {
        concArray[i] = concYrLine;
    }
    else
    {
        concYrLine = sr.ReadLine();
    }
}
Andy Clark
  • 3,363
  • 7
  • 27
  • 42
  • The thing is though, it's not null. Whenever I just read in all of the lines into the array and print them out, it prints out all of the lines perfectly – rcarcia02 Apr 05 '18 at 18:19
  • Also, `concYrLine.Contains("EHRS") == true` is verbose, there is no need for the `== true` as the `Contains` method returns a boolean already – Andy Clark Apr 05 '18 at 18:19
  • My Assumption is it must be null, as this article which explains why the exception is thrown https://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx When you say you "print them out", where are you printing them? – Andy Clark Apr 05 '18 at 19:06