Greg
Greg

Reputation:

StreamReader looking for file in the wrong directory in C#

I have a program where I am using windows form, in that form I use openFileDialog where I open a file in some directory. Then I use in a different function a StreamReader and I have a 2nd file in my big/debug directory which I want the streamReader to open. But for some reason after I open the 1st file with the openFileDialog the StreamReader looks for the 2nd file in that directory instead in bin/debug as usual.

Does anyone know why he does that and how can I solve it?

Thanks in advance,

Greg

Upvotes: 1

Views: 1791

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

The OpenFileDialog has that behavior; it alters the current directory for the application. To prevent this from happening, you can use the RestoreDirectory property of the OpenFileDialog.

Upvotes: 1

Guffa
Guffa

Reputation: 700312

If you don't specify a complete file path but only a file name, that means that the file is in the current directory. When you use the OpenFileDialog, it changes the current directory.

If you want to access a file somewhere regardless of what the current directory is set to, you have to specify a complete path for it. You can use Application.StartupPath to get the path to the folder where your program is.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838156

When you change directory in an open file dialog, this also causes your application's working directory to change. So if you are trying to use relative paths, it will look in the wrong place.

The solution is RestoreDirectory.

Upvotes: 1

Related Questions