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

C# 如何从路径中提取每个文件夹名称?,c#,string,C#,String,我的路径是\\server\folderName1\other name\something\other folder\ 如果我不知道路径中有多少文件夹,也不知道文件夹名称,如何将每个文件夹名称提取为字符串 非常感谢快速的答案是使用.Split('\\')方法。可能在循环中调用?如果您想要每个目录的完整路径,而不仅仅是目录名,那么就需要这样做 string mypath = @"..\folder1\folder2\folder2"; string[] directories = mypath.

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

如果我不知道路径中有多少文件夹,也不知道文件夹名称,如何将每个文件夹名称提取为字符串


非常感谢

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

可能在循环中调用?如果您想要每个目录的完整路径,而不仅仅是目录名,那么就需要这样做

string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
编辑: 这将返回目录数组中的每个单独文件夹。您可以按如下方式获取返回的文件夹数:

int folderCount = directories.Length;
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
}

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

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

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

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

这在一般情况下很好:

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

int folderCount = directories.Length;
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
}
我相信这涵盖了所有的基础,不会太迂腐。它将返回一个
string[]
,您可以使用
foreach
迭代该字符串,依次获取每个目录

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

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

然后使用
分隔符
而不是上面代码中的
@“\/”
。就我个人而言,我觉得这太冗长了,很可能不会这么做。

我写了下面的方法,它对我很有效

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;
    }
与您的问题最相关的是:

DirectoryInfo directories=newdirectoryinfo(@path); DirectoryInfo[]folderList=目录。GetDirectories()


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

我将添加到Matt Brunell的答案中

            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;
                        }
                    }
                }
            }
这应该给你:

“\server”

“\server\folderName1”

“\server\folderName1\其他名称”

“\server\folderName1\other name\something”

“\server\folderName1\other name\something\other folder\”


(或按字符串对结果集合进行排序。每个值的长度。

意识到这是一篇老文章,但我无意中发现了它-最后我决定使用下面的函数,因为它对我当时所做的事情进行了比上面任何一个都好的排序:

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;
}
私有静态列表拆分目录(DirectoryInfo父目录)
{
if(parent==null)返回null;
var rtn=新列表();
var di=父母;
while(di.Name!=di.Root.Name)
{
rtn.Add(新目录信息(di));
di=di.父母;
}
添加(新目录信息(di.Root));
rtn.Reverse();
返回rtn;
}
/------------------------------------------------------------------------------------
/// 
///用于模拟C库函数_splitpath()
/// 
///分裂之路
///如果是相对路径,则可选根
///路径中的文件夹。
///项0是带“:”的驱动器号
///如果路径为UNC路径,则项目0为“\\”
/// 
/// 
///字符串p1=@“c:\p1\p2\p3\p4”;
///字符串[]ap1=p1.SplitPath();
/////ap1={c:,“p1”,“p2”,“p3”,“p4”}
///字符串p2=@“\\server\p2\p3\p4”;
///字符串[]ap2=p2.SplitPath();
/////ap2={@“\\”,“服务器”,“p2”,“p3”,“p4”}
///字符串p3=@.\p3\p4”;
///字符串root3=@“c:\p1\p2\”;
///字符串[]ap3=p1.SplitPath(root3);
/////ap3={c:,“p1”,“p3”,“p4”}
/// 
公共静态字符串[]拆分路径(此字符串路径,字符串根路径=)
{
串驱;
字符串[]astr;
path=path.GetFullPath(path.Combine(rootpath,path));
如果(路径[1]==':')
{
驱动器=路径子字符串(0,2);
字符串newpath=path.Substring(2);
astr=newpath.Split(new[]{Path.directoryseportorchar}
,StringSplitOptions.RemoveEmptyEntries);
}
其他的
{
驱动器=@“\\”;
astr=path.Split(新[]{path.directoryseportorchar}
,StringSplitOptions.RemoveEmptyEntries);
}
字符串[]拆分路径=新字符串[astr.Length+1];
splitPath[0]=驱动器;
应收账款副本(拆分路径,1);
返回路径;
}
我看到了你的父母,把你抚养成人

internal static List<DirectoryInfo> Split(this DirectoryInfo path)
{
    if(path == null) throw new ArgumentNullException("path");
    var ret = new List<DirectoryInfo>();
    if (path.Parent != null) ret.AddRange(Split(path.Parent));
    ret.Add(path);
    return ret;
}
会回来的

c:\

folder1

folder2

folder3

公共静态IEnumerable拆分(此目录信息路径)
public static IEnumerable<string> Split(this DirectoryInfo path)
{
    if (path == null) 
        throw new ArgumentNullException("path");
    if (path.Parent != null)
        foreach(var d in Split(path.Parent))
            yield return d;
    yield return path.Name;
}
{ if(路径==null) 抛出新的ArgumentNullException(“路径”); 如果(path.Parent!=null) foreach(拆分中的变量d(path.Parent)) 收益率d; 返回路径名; }
以下是对Wolf答案的修改,它去掉了根,并修复了一些似乎是错误的地方。我用它生成了一个面包屑,我不想让根显示出来

这是
DirectoryInfo
类型的扩展

公共静态列表PathParts(此DirectoryInfo源,字符串根路径)
{
if(source==null)返回null;
DirectoryInfo根=新的DirectoryInfo(根路径);
var pathParts=新列表();
var di=来源;
while(di!=null&&di.FullName!=root.FullName)
{
pathParts.Add(di);
di=di.父母;
}
pathParts.Reverse();
返回路径部件;
}

我刚刚编写了此代码,因为我没有找到任何已内置的C#

//
///拿到di
public static IEnumerable<string> Split(this DirectoryInfo path)
{
    if (path == null) 
        throw new ArgumentNullException("path");
    if (path.Parent != null)
        foreach(var d in Split(path.Parent))
            yield return d;
    yield return path.Name;
}
/// <summary>
/// get the directory path segments.
/// </summary>
/// <param name="directoryPath">the directory path.</param>
/// <returns>a IEnumerable<string> containing the get directory path segments.</returns>
public IEnumerable<string> GetDirectoryPathSegments(string directoryPath)
{
    if (string.IsNullOrEmpty(directoryPath))
    { throw new Exception($"Invalid Directory: {directoryPath ?? "null"}"); }

    var currentNode = new System.IO.DirectoryInfo(directoryPath);

    var targetRootNode = currentNode.Root;
    if (targetRootNode == null) return new string[] { currentNode.Name };
    var directorySegments = new List<string>();
    while (string.Compare(targetRootNode.FullName, currentNode.FullName, StringComparison.InvariantCultureIgnoreCase) != 0)
    {
        directorySegments.Insert(0, currentNode.Name);
        currentNode = currentNode.Parent;
    }
    directorySegments.Insert(0, currentNode.Name);
    return directorySegments;
}
    /// <summary>
    /// Split a directory in its components.
    /// Input e.g: a/b/c/d.
    /// Output: d, c, b, a.
    /// </summary>
    /// <param name="Dir"></param>
    /// <returns></returns>
    public static IEnumerable<string> DirectorySplit(this DirectoryInfo Dir)
    {
        while (Dir != null)
        {
            yield return Dir.Name;
            Dir = Dir.Parent;
        }
    }
    /// <summary>
    /// Return one part of the directory path.
    /// Path e.g.: a/b/c/d. PartNr=0 is a, Nr 2 = c.
    /// </summary>
    /// <param name="Dir"></param>
    /// <param name="PartNr"></param>
    /// <returns></returns>
    public static string DirectoryPart(this DirectoryInfo Dir, int PartNr)
    {
        string[] Parts = Dir.DirectorySplit().ToArray();
        int L = Parts.Length;
        return PartNr >= 0 && PartNr < L ? Parts[L - 1 - PartNr] : "";
    }
    DirectoryInfo DI_Data = new DirectoryInfo(@"D:\Hunter\Data\2019\w38\abc\000.d");
    label_Year.Text = DI_Data.DirectoryPart(3); // --> 2019
    label_Entry.Text = DI_Data.DirectoryPart(6);// --> 000.d