How does one extract each folder name from a path?

后端 未结 16 1601
傲寒
傲寒 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:22

    I am adding to Matt Brunell's answer.

                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;
                            }
                        }
                    }
                }
    

    This should give you:

    "\server"

    "\server\folderName1"

    "\server\folderName1\another name"

    "\server\folderName1\another name\something"

    "\server\folderName1\another name\something\another folder\"

    (or sort your resulting collection by the string.Length of each value.

提交回复
热议问题