How does one extract each folder name from a path?

后端 未结 16 1540
傲寒
傲寒 2020-11-30 09:18

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

How do I extract each folder name into a string if I don\'t know how many

相关标签:
16条回答
  • 2020-11-30 10:10

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 10:10

    I just coded this since I didn't find any already built in in C#.

    /// <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;
    }
    
    0 讨论(0)
  • 2020-11-30 10:13
    DirectoryInfo objDir = new DirectoryInfo(direcotryPath);
    DirectoryInfo [] directoryNames =  objDir.GetDirectories("*.*", SearchOption.AllDirectories);
    

    This will give you all the directories and subdirectories.

    0 讨论(0)
  • 2020-11-30 10:14
    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;
    
    0 讨论(0)
  • 2020-11-30 10:14

    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.

    0 讨论(0)
  • 2020-11-30 10:16

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

    0 讨论(0)
提交回复
热议问题