【问题标题】:Get a folder name from a path从路径中获取文件夹名称
【发布时间】:2011-01-25 08:38:43
【问题描述】:

我有一些路径c:\server\folderName1\another name\something\another folder\

如何从那里提取最后一个文件夹名称?

我尝试了几件事,但都没有成功。

我只是不想搜索最后一个\,然后再拿其余的。

谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:
    string a = new System.IO.DirectoryInfo(@"c:\server\folderName1\another name\something\another folder\").Name;
    

    【讨论】:

    • 真遗憾这在 Intellisense 提示中没有更明显地描述! :)
    【解决方案2】:

    DirectoryInfo.Name 工作:

    using System;
    using System.IO;
    
    class Test
    {
        static void Main()
        {
            DirectoryInfo info = new DirectoryInfo("c:\\users\\jon\\test\\");
            Console.WriteLine(info.Name); // Prints test
        }                                                
    }
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        也可以使用 System.IO.Path:

        string s = Path.GetFileName(Path.GetDirectoryName(@"c:\server\folderName1\another name\something\another folder\"));
        

        【讨论】:

          【解决方案5】:

          使用这一行 System.Linq 命令:

          foldername.Split(Path.DirectorySeparatorChar).Reverse().ToArray()[0]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-04-13
            • 2011-07-10
            • 1970-01-01
            • 2016-12-29
            • 2020-03-16
            • 1970-01-01
            相关资源
            最近更新 更多