如何向上导航几个文件夹

本文关键字:几个 文件夹 导航 | 更新日期: 2023-09-27 17:59:27

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

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

如何向上导航几个文件夹

其他简单的方法是:

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

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

附加说明Path.GetFullPath根据您的代码在windows/mac/mobile/上运行的环境来规范化最终结果。。。

如果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''

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

您也可以使用Path类。

C#路径类

这是最适合我的:

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

获取"正确"路径不是问题,添加"../"显然是这样做的,但在那之后,给定的字符串就不可用了,因为它只会添加"../"最后。用Path.GetFullPath()包围它会给你一条绝对的路径,使它可用。

public static string AppRootDirectory()
        {
            string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..'..'"));
        }

以下方法搜索以应用程序启动路径(*.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.StartupPathPath.GetDirectoryName(Assembly.GetExecutingAssembly().Location)(如果您愿意)。

我使用此策略来查找配置和资源文件。这使我可以通过将它们放在一个通用的父文件夹中,为多个应用程序或应用程序的调试和发布版本共享它们。

如果您想声明级别数并将其放入函数中,那么您可以使用函数吗?

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

C#

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

隐藏对Directory.GetParent(路径)的循环调用是一种方法。

用"和路径。合并最终会导致与操作系统相关的错误,或者只是由于相对路径和绝对路径之间的混淆而失败。

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;
    }
}

这可能有助于

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

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

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

我有一些虚拟目录,不能使用Directory方法。因此,我为感兴趣的人制作了一个简单的拆分/联接函数。不过不那么安全。

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

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

可以通过System.IO.Directory.GetParent进行路径解析,但需要多次运行相同的函数。

稍微简单一点的方法是将威胁路径作为一个普通字符串,用路径分隔符将其拆分,去掉不需要的部分,然后重新组合字符串。

var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));

当然,您可以用需要跳起来的级别数量来替换2

还请注意,此函数对Path.GetFullPath的调用(此处的其他答案)将使用文件系统查询路径是否存在。使用基本字符串操作不需要任何文件系统操作。