views:

77

answers:

3

Hi all i have doen a code to retrieve direcotry path in 2 different forms. If in one form if i select a path to open a file and finished and when coming back to the other form i am getting an error as Direcotry Exception. But i used to different strings to get that path

like in my 2nd form i called this

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

Where as in my first form i am having

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

But while i debug i am getting the selected path from the second form but not the path i required can any one tell why...

+3  A: 

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.

Greets Flo

Florian Reischl
I am using Openfiledialog can you suggest how to over come this.
Dorababu
See Mark's good explanation :-)
Florian Reischl
+6  A: 

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");
0xA3
+3  A: 

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.

Marc Gravell