C# 如何从路径中提取每个文件夹名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/401304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:04:25  来源:igfitidea点击:

How does one extract each folder name from a path?

c#string

提问by

My path is \\server\folderName1\another name\something\another folder\

我的路径是 \\server\folderName1\another name\something\another folder\

How do I extract each folder name into a string if I don't know how many folders there are in the path and I don't know the folder names?

如果我不知道路径中有多少个文件夹并且我不知道文件夹名称,如何将每个文件夹名称提取到一个字符串中?

Many thanks

非常感谢

回答by Mark A Johnson

The quick answer is to use the .Split('\\') method.

快速回答是使用 .Split('\\') 方法。

回答by Brian

Maybe call Directory.GetParentin a loop? That's if you want the full path to each directory and not just the directory names.

也许循环调用Directory.GetParent?那是如果您想要每个目录的完整路径而不仅仅是目录名称。

回答by Matt Brunell

string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);

Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:

编辑:这将返回目录数组中的每个单独文件夹。您可以像这样获得返回的文件夹数:

int folderCount = directories.Length;

回答by M4N

Or, if you need to do something with each folder, have a look at the System.IO.DirectoryInfo class. It also has a Parent property that allows you to navigate to the parent directory.

或者,如果您需要对每个文件夹执行某些操作,请查看 System.IO.DirectoryInfo 类。它还有一个 Parent 属性,允许您导航到父目录。

回答by Dan Herbert

There are a few ways that a file path can be represented. You should use the System.IO.Pathclass to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:

有几种方法可以表示文件路径。您应该使用System.IO.Path该类来获取操作系统的分隔符,因为它在 UNIX 和 Windows 之间可能有所不同。此外,无论操作系统如何,大多数(或所有,如果我没记错的话).NET 库都接受“\”或“/”作为路径分隔符。出于这个原因,我会使用 Path 类来分割你的路径。尝试类似以下内容:

string originalPath = "\server\folderName1\another\ name\something\another folder\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                              Path.DirectorySeparatorChar);

This should work regardless of the number of folders or the names.

无论文件夹数量或名称如何,这都应该有效。

回答by Jon

This is good in the general case:

这在一般情况下很好:

yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries)

There is no empty element in the returned array if the path itself ends in a (back)slash (e.g. "\foo\bar\"). However, you will have to be sure that yourPathis really a directory and not a file. You can find out what it is and compensate if it is a file like this:

如果路径本身以(反)斜杠(例如“\foo\bar\”)结尾,则返回的数组中没有空元素。但是,您必须确保它yourPath确实是一个目录而不是文件。您可以找出它是什么并补偿它是否是这样的文件:

if(Directory.Exists(yourPath)) {
  var entries = yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries);
}
else if(File.Exists(yourPath)) {
  var entries = Path.GetDirectoryName(yourPath).Split(
                    @"\/", StringSplitOptions.RemoveEmptyEntries);
}
else {
  // error handling
}

I believe this covers all bases without being too pedantic. It will return a string[]that you can iterate over with foreachto get each directory in turn.

我相信这涵盖了所有基础而不会太迂腐。它将返回一个string[],您可以迭代它foreach以依次获取每个目录。

If you want to use constants instead of the @"\/"magic string, you need to use

如果要使用常量而不是@"\/"魔术字符串,则需要使用

var separators = new char[] {
  Path.DirectorySeparatorChar,  
  Path.AltDirectorySeparatorChar  
};

and then use separatorsinstead of @"\/"in the code above. Personally, I find this too verbose and would most likely not do it.

然后在上面的代码中使用separators而不是@"\/"。就个人而言,我觉得这太冗长了,很可能不会这样做。

回答by steve_mtl

I wrote the following method which works for me.

我写了以下对我有用的方法。

protected bool isDirectoryFound(string path, string pattern)
    {
        bool success = false;

        DirectoryInfo directories = new DirectoryInfo(@path);
        DirectoryInfo[] folderList = directories.GetDirectories();

        Regex rx = new Regex(pattern);

        foreach (DirectoryInfo di in folderList)
        {
            if (rx.IsMatch(di.Name))
            {
                success = true;
                break;
            }
        }

        return success;
    }

The lines most pertinent to your question being:

与您的问题最相关的几行是:

DirectoryInfo directories = new DirectoryInfo(@path); DirectoryInfo[] folderList = directories.GetDirectories();

DirectoryInfo 目录 = new DirectoryInfo(@path); DirectoryInfo[] folderList = directory.GetDirectories();

回答by Navish Rampal

DirectoryInfo objDir = new DirectoryInfo(direcotryPath);
DirectoryInfo [] directoryNames =  objDir.GetDirectories("*.*", SearchOption.AllDirectories);

This will give you all the directories and subdirectories.

这将为您提供所有目录和子目录。

回答by granadaCoder

I am adding to Matt Brunell's answer.

我正在补充马特布鲁内尔的答案。

            string[] directories = myStringWithLotsOfFolders.Split(Path.DirectorySeparatorChar);

            string previousEntry = string.Empty;
            if (null != directories)
            {
                foreach (string direc in directories)
                {
                    string newEntry = previousEntry + Path.DirectorySeparatorChar + direc;
                    if (!string.IsNullOrEmpty(newEntry))
                    {
                        if (!newEntry.Equals(Convert.ToString(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteLine(newEntry);
                            previousEntry = newEntry;
                        }
                    }
                }
            }

This should give you:

这应该给你:

"\server"

“\服务器”

"\server\folderName1"

“\服务器\文件夹名称1”

"\server\folderName1\another name"

"\server\folderName1\another name"

"\server\folderName1\another name\something"

"\server\folderName1\another name\something"

"\server\folderName1\another name\something\another folder\"

"\server\folderName1\another name\something\another folder\"

(or sort your resulting collection by the string.Length of each value.

(或按每个值的 string.Length 对结果集合进行排序。

回答by Wolf5370

Realise this is an old post, but I came across it looking - in the end I decided apon the below function as it sorted what I was doing at the time better than any of the above:

意识到这是一篇旧帖子,但我发现它看起来 - 最后我决定使用以下功能,因为它比上述任何一个都更好地对我当时正在做的事情进行排序:

private static List<DirectoryInfo> SplitDirectory(DirectoryInfo parent)
{
    if (parent == null) return null;
    var rtn = new List<DirectoryInfo>();
    var di = parent;

    while (di.Name != di.Root.Name)
    {
    rtn.Add(new DirectoryInfo(di));
    di = di.Parent;
    }
    rtn.Add(new DirectoryInfo(di.Root));

    rtn.Reverse();
    return rtn;
}