How does one extract each folder name from a path?

后端 未结 16 1539
傲寒
傲寒 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<DirectoryInfo> PathParts(this DirectoryInfo source, string rootPath)
    {
      if (source == null) return null;
      DirectoryInfo root = new DirectoryInfo(rootPath);
      var pathParts = new List<DirectoryInfo>();
      var di = source;
    
      while (di != null && di.FullName != root.FullName)
      {
        pathParts.Add(di);
        di = di.Parent;
      }
    
      pathParts.Reverse();
      return pathParts;
    }
    
    0 讨论(0)
  • 2020-11-30 10:01

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

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

    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();

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

    There are a few ways that a file path can be represented. You should use the System.IO.Path class 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:

    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.

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

    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 yourPath is really a directory and not a file. You can find out what it is and compensate if it is a file like this:

    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 foreach to get each directory in turn.

    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 separators instead of @"\/" in the code above. Personally, I find this too verbose and would most likely not do it.

    0 讨论(0)
  • 2020-11-30 10:08
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        /// <summary>
        /// Use to emulate the C lib function _splitpath()
        /// </summary>
        /// <param name="path">The path to split</param>
        /// <param name="rootpath">optional root if a relative path</param>
        /// <returns>the folders in the path. 
        ///     Item 0 is drive letter with ':' 
        ///     If path is UNC path then item 0 is "\\"
        /// </returns>
        /// <example>
        /// string p1 = @"c:\p1\p2\p3\p4";
        /// string[] ap1 = p1.SplitPath();
        /// // ap1 = {"c:", "p1", "p2", "p3", "p4"}
        /// string p2 = @"\\server\p2\p3\p4";
        /// string[] ap2 = p2.SplitPath();
        /// // ap2 = {@"\\", "server", "p2", "p3", "p4"}
        /// string p3 = @"..\p3\p4";
        /// string root3 = @"c:\p1\p2\";
        /// string[] ap3 = p1.SplitPath(root3);
        /// // ap3 = {"c:", "p1", "p3", "p4"}
        /// </example>
        public static string[] SplitPath(this string path, string rootpath = "")
        {
            string drive;
            string[] astr;
            path = Path.GetFullPath(Path.Combine(rootpath, path));
            if (path[1] == ':')
            {
                drive = path.Substring(0, 2);
                string newpath = path.Substring(2);
                astr = newpath.Split(new[] { Path.DirectorySeparatorChar }
                    , StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                drive = @"\\";
                astr = path.Split(new[] { Path.DirectorySeparatorChar }
                    , StringSplitOptions.RemoveEmptyEntries);
            }
            string[] splitPath = new string[astr.Length + 1];
            splitPath[0] = drive;
            astr.CopyTo(splitPath, 1);
            return splitPath;
        }
    
    0 讨论(0)
提交回复
热议问题