How does one extract each folder name from a path?

后端 未结 16 1600
傲寒
傲寒 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

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

    /// 
    /// get the directory path segments.
    /// 
    /// the directory path.
    /// a IEnumerable containing the get directory path segments.
    public IEnumerable 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();
        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;
    }
    

提交回复
热议问题