Why is my file not found or opened?

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)"

Upvotes: 0

Views: 207

Answers (2)

jason
jason

Reputation: 241641

That doesn't make sense. I'm not aware of any scenario in which File.OpenText returns successfully and the return value is null. If File.OpenText can not find the file, it throws a FileNotFoundException.

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.ReadLine and then checking if the line contains "host=". But it could be the case that you've reached the end of the stream in which case line will be null and you'll throw. One way to rewrite your loop is to say

while ((line = reader.ReadLine()) != null) {
    if (line.Contains("host=")) {
    }
}

I'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

Console.WriteLine(reader == null);

which you will place immediately before the

line = reader.ReadLine();

line.

Upvotes: 6

Thousand
Thousand

Reputation: 6638

try using the full path to the file:

  using (StreamReader sr = new StreamReader("c:\\Users\\fullpath\\file.txt"))

Upvotes: 1

Related Questions