How does one extract each folder name from a path?

后端 未结 16 1597
傲寒
傲寒 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 09:55

    Here's a modification of Wolf's answer that leaves out the root and fixes what seemed to be a couple of bugs. I used it to generate a breadcrumbs and I didn't want the root showing.

    this is an extension of the DirectoryInfo type.

    public static List PathParts(this DirectoryInfo source, string rootPath)
    {
      if (source == null) return null;
      DirectoryInfo root = new DirectoryInfo(rootPath);
      var pathParts = new List();
      var di = source;
    
      while (di != null && di.FullName != root.FullName)
      {
        pathParts.Add(di);
        di = di.Parent;
      }
    
      pathParts.Reverse();
      return pathParts;
    }
    

提交回复
热议问题