【问题标题】:How to navigate a few folders up?如何向上导航几个文件夹?
【发布时间】:2013-01-31 16:57:40
【问题描述】:

一种选择是执行 System.IO.Directory.GetParent() 几次。有没有更优雅的方式从执行程序集所在的位置向上移动几个文件夹?

我要做的是找到一个文本文件,该文件位于应用程序文件夹上方的一个文件夹中。但程序集本身在 bin 内,即应用程序文件夹深处的几个文件夹。

【问题讨论】:

  • 通常相对路径会起到类似 '..\..\..\..\Downfolder' 之类的作用,但这取决于您究竟要为...做什么?
  • 总是这样吗?
  • “导航”如何?你是说当前目录吗?如果是这样,你应该可以做到Directory.SetCurrentDirectory(@"..\..\..\..");

标签: c# .net console-application


【解决方案1】:

其他简单的方法是这样做:

string path = @"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));

注意这上升了两个级别。结果将是: newPath = @"C:\Folder1\Folder2\";

【讨论】:

  • 无论如何手动添加反斜杠时,使用Path.Combine 毫无意义。考虑改用Path.Combine(path, "..", "..")
  • @AXMIM 使用 GetFullPath 将返回绝对路径,这在大多数情况下都会有所不同。尝试在 CodeBunk 中输入上述代码,如果不使用 GetFullPath,结果会有所不同,并且在大多数情况下可能会导致错误。
  • 这适用于任何操作系统还是仅适用于某些在路径中使用反斜杠的特定操作系统,例如 Windows?
  • @alcoholisevil 我在 Windows 上测试过,不确定 Mac,我想它也应该在 mac 上工作。 (getFullPath 应该为每个环境/操作系统规范化路径字符串)
  • 您也可以将它们组合起来(可能会更好):Path.GetFullPath(Path.Combine(path, "..", ".."))
【解决方案2】:

如果 c:\folder1\folder2\folder3\bin 是路径,那么下面的代码将返回 bin 文件夹的路径基文件夹

//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());

string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();

即,c:\folder1\folder2\folder3

如果你想要folder2路径,那么你可以通过

获取目录
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();

那么你会得到路径为 c:\folder1\folder2\

【讨论】:

    【解决方案3】:

    您可以使用..\path 上一级,..\..\path 可以从路径上上两级。

    您也可以使用Path 类。

    C# Path class

    【讨论】:

      【解决方案4】:

      这是最适合我的:

      string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

      获取“正确”路径不是问题,添加 '../' 显然可以做到这一点,但在那之后,给定的字符串将不可用,因为它只会添加 '../' 在结尾。 用Path.GetFullPath() 包围它会给你绝对路径,使它可用。

      【讨论】:

        【解决方案5】:
        public static string AppRootDirectory()
                {
                    string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
                }
        

        【讨论】:

          【解决方案6】:

          如果你想声明层数并将其放入一个函数中,也许你可以使用一个函数?

          private String GetParents(Int32 noOfLevels, String currentpath)
          {
               String path = "";
               for(int i=0; i< noOfLevels; i++)
               {
                   path += @"..\";
               }
               path += currentpath;
               return path;
          }
          

          你可以这样称呼它:

          String path = this.GetParents(4, currentpath);
          

          【讨论】:

            【解决方案7】:

            以下方法搜索以应用程序启动路径(*.exe 文件夹)开头的文件。如果在那里找不到文件,则会搜索父文件夹,直到找到文件或到达根文件夹。如果找不到文件,则返回null

            public static FileInfo FindApplicationFile(string fileName)
            {
                string startPath = Path.Combine(Application.StartupPath, fileName);
                FileInfo file = new FileInfo(startPath);
                while (!file.Exists) {
                    if (file.Directory.Parent == null) {
                        return null;
                    }
                    DirectoryInfo parentDir = file.Directory.Parent;
                    file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
                }
                return file;
            }
            

            注意:Application.StartupPath 通常用于 WinForms 应用程序,但也适用于控制台应用程序;但是,您必须设置对System.Windows.Forms 程序集的引用。如果您愿意,可以将Application.StartupPath 替换为
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

            【讨论】:

              【解决方案8】:

              C#

              string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, @"..\..\"));
              

              【讨论】:

                【解决方案9】:

                在静态方法中隐藏对 Directory.GetParent(path) 的循环调用是可行的方法。

                乱用“..”和 Path.Combine 最终会导致与操作系统相关的错误,或者由于相对路径和绝对路径之间的混淆而导致失败。

                public static class PathUtils
                {
                    public static string MoveUp(string path, int noOfLevels)
                    {
                        string parentPath = path.TrimEnd(new[] { '/', '\\' });
                        for (int i=0; i< noOfLevels; i++)
                        {
                            parentPath = Directory.GetParent(parentPath ).ToString();
                        }
                        return parentPath;
                    }
                }
                

                【讨论】:

                  【解决方案10】:

                  这可能会有所帮助

                  string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
                  if (File.Exists(parentOfStartupPath))
                  {
                      // file found
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    如果您知道要导航到的文件夹,请找到它的索引,然后找到子字符串。

                                var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
                    
                                string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
                    

                    【讨论】:

                    • 这在 这么多 种情况下都失败了。例如,如果文件夹的名称只是 a 怎么办?如果路径看起来像这样C:\Folderame3\Folderame2\Folderame\...怎么办?
                    • 如果文件夹名称只是搜索 "\\a\\" 或 \\a 如果是最后一个
                    【解决方案12】:

                    我有一些虚拟目录,我不能使用目录方法。所以,我为那些感兴趣的人做了一个简单的拆分/连接功能。不过没那么安全。

                    var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
                    var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
                    

                    所以,如果你想将 4 向上移动,你只需要将 1 更改为 4 并添加一些检查以避免异常。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2020-07-30
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多