2010-07-21 84 views
3

我有代码以2种不同的形式检索direcotry路径。如果在一种形式中,我选择一个路径来打开一个文件并处理它,当返回到另一个表单时,我得到一个Direcotry Exception错误。我用不同的字符串来获取路径为什么路径发生变化

在第二种形式我叫这个:

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

在我的第一个形式我叫:

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

在调试过程中,我得到的选择第二种形式的路径,但不是我期望的路径。任何人都可以说明原因吗?

+0

请在问题中加入例外。 – 2010-07-21 08:41:10

回答

8

您是否检查当前目录的值?

OpenFileDialog通常会改变当前目录。您可以使用RestoreDirectory属性来控制这种行为:

OpenFileDialog ofd = new OpenFileDialog(); 

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

顺便说一句,你是串联您的代码示例中的路径。在.NET中,最好使用静态的Path.Combine方法完成。此方法将检查一个反斜杠(或其他系统的路径分隔符),并自动存在插入一个如果它缺少:

strFilePath = Path.Combine(strFilePath, "ACH"); 
3

通常这取决于拨打电话FolderBrowserDialogOpenFileDialog或类似的东西。这些对话框(以及其他组件)会自动更改正在运行的应用程序的工作目录。

我的建议是避免使用相对路径,如果有任何种类的用户交互。

+0

我使用Openfiledialog,你可以建议如何过来这个。 – Dotnet 2010-07-21 08:47:57

+0

请看Mark的好解释:-) – 2010-07-21 09:02:10

3

OpenFileDialogSaveFileDialog改变当前的工作路径,这是很烦人的。您可以手动重置该选项,也可以设置.RestoreDirectory = true;以在选择文件后更改它。如果您使用的是FolderBrowserDialog,如果您仍然遇到此问题,则必须手动执行此操作。

相关问题