I added a .txt file to the \bin\Debug folder, and am trying to open it and read from it like so:
using (StreamReader reader = File.OpenText("Credentials.txt")) {
string line = null;
do {
line = reader.ReadLine();
if (line.Contains("host=")) {
. . .
But, although the file is there, when I get to the “ReadLine()” line, it stops dead in its tracks with:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
UPDATE
I had to change it from “do...while (line != null);” to “while (! reader.EndOfStream)“
That doesn’t make sense. I’m not aware of any scenario in which
File.OpenTextreturns successfully and the return value isnull. IfFile.OpenTextcan not find the file, it throws aFileNotFoundException.Are you sure that the line you state is actually the line throwing the exception? Please check the stack trace carefully.
Note that your loop is in the wrong order. You’re calling
StreamReader.ReadLineand then checking if the line contains “host=”. But it could be the case that you’ve reached the end of the stream in which caselinewill be null and you’ll throw. One way to rewrite your loop is to sayI’m not saying this is the best way (I don’t think it is), but it is a common idiom in C#.
If you insist that you’re correct, please print the output of
which you will place immediately before the
line.