views:

267

answers:

3

Hello,

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

+1  A: 

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.

Mark Byers
+1  A: 

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.

Fredrik Mörk
Thank you very much, that did the trick!
A: 

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.

Guffa