代码之家  ›  专栏  ›  技术社区  ›  Developer

为什么要改变道路

  •  3
  • Developer  · 技术社区  · 14 年前

    我有两种不同形式的检索目录路径的代码。如果在一个表单中,我选择一个路径打开一个文件并处理它,当返回到另一个表单时,我会得到一个direcotry异常错误。我以前用不同的弦来获得那条路

    在第二种形式中,我称之为:

           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;
    

    在调试期间,我从第二个窗体中获取所选路径,但不是我期望的路径。有人知道为什么吗?

    3 回复  |  直到 13 年前
        1
  •  8
  •   Dirk Vollmar    14 年前

    您检查了当前目录的值吗?

    这个 OpenFileDialog 通常会更改当前目录。您可以使用 RestoreDirectory 财产:

    OpenFileDialog ofd = new OpenFileDialog();
    
    ofd.RestoreDirectory = true ; // this will not modify the current directory
    

    顺便提一句,您正在代码示例中连接路径。在.NET中,最好使用静态 Path.Combine 方法。此方法将检查是否存在反斜杠(或无论系统的路径分隔符是什么),如果缺少,则自动插入一个反斜杠:

    strFilePath = Path.Combine(strFilePath, "ACH");
    
        2
  •  3
  •   Marc Gravell    14 年前

    OpenFileDialog SaveFileDialog 改变当前的工作路径,这很烦人。您可以手动重置,也可以设置 .RestoreDirectory = true; 以使其在选择文件后变回原来的状态。如果您正在使用 FolderBrowserDialog 如果你仍然有这个问题,你必须手动操作。

        3
  •  3
  •   Tim Cooper    13 年前

    通常这取决于 FolderBrowserDialog A OpenFileDialog 或者类似的东西。这些对话框(和其他组件)会自动更改正在运行的应用程序的工作目录。

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