开发者

Why the path is getting changed

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).To开发者_运维问答String();
       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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜