Take the 2-minute tour ×

I have code which retrieves a direcotry path in 2 different forms. If, in one form, I select a path to open a file and process it, when returning to the other form I am getting a Direcotry Exception error. I used to different strings to get that path

In the second form I called this:

       string strFilePath2;
       strFilePath2 = Directory.GetCurrentDirectory();
       strFilePath2 = Directory.GetParent(strFilePath2).ToString();
       strFilePath2 = Directory.GetParent(strFilePath2).ToString();
       strFilePath2 = strFilePath2 + "\\ACH";

In my first form I called:

       strFilePath = Directory.GetCurrentDirectory();
       strFilePath = Directory.GetParent(strFilePath).ToString();
       strFilePath = Directory.GetParent(strFilePath).ToString();
       strFilePath = strFilePath + "\\ACH\\" + Node;

During debugging, I am getting the selected path from the second form, but not the path I expected. Can any one tell why?

share|improve this question
Please put the exception in the question. –  Preet Sangha Jul 21 '10 at 8:41

3 Answers 3

up vote 8 down vote accepted

Did you check the value of the current directory?

The OpenFileDialog usually will change the current directory. You can control that behavior using the RestoreDirectory property:

OpenFileDialog ofd = new OpenFileDialog();

ofd.RestoreDirectory = true ; // this will not modify the current directory

As an aside, you are concatenating paths in your code sample. In .NET this is best done using the static Path.Combine method. This method will check for the presence of a backslash (or whatever the system's path separator character is) and automatically insert one if it is missing:

strFilePath = Path.Combine(strFilePath, "ACH");
share|improve this answer

Often this depends on a call of a FolderBrowserDialog, a OpenFileDialog or something alike. These dialogs (and other components) automatically change the working directory of your running application.

My advice is to avoid using relative pathes if there is any kind of user interaction.

share|improve this answer
I am using Openfiledialog can you suggest how to over come this. –  Dotnet Jul 21 '10 at 8:47
See Mark's good explanation :-) –  Florian Reischl Jul 21 '10 at 9:02

OpenFileDialog and SaveFileDialog change the current working path, which is very annoying. You can either reset this manually, or set .RestoreDirectory = true; to get it to change back after selecting the file. If you are using FolderBrowserDialog you'll have to do it manually if you still get this issue.

share|improve this answer

Your Answer


