C# 从路径获取文件夹名称

C# 从路径获取文件夹名称,c#,path,filesystems,C#,Path,Filesystems,我可以使用哪些对象或方法来获得folder2的结果?我可能会使用以下方法: string path = "C:/folder1/folder2/file.txt"; 对GetDirectoryName的内部调用将返回完整路径,而对GetFileName()的外部调用将返回最后一个路径组件,即文件夹名称 无论路径是否实际存在,这种方法都有效。然而,这种方法依赖于最初以文件名结尾的路径。如果不知道路径是否以文件名或文件夹名结尾,则需要首先检查实际路径以查看该位置是否存在文件/文件夹。在这种情况下,

我可以使用哪些对象或方法来获得
folder2
的结果?

我可能会使用以下方法:

string path = "C:/folder1/folder2/file.txt";
GetDirectoryName
的内部调用将返回完整路径,而对
GetFileName()
的外部调用将返回最后一个路径组件,即文件夹名称


无论路径是否实际存在,这种方法都有效。然而,这种方法依赖于最初以文件名结尾的路径。如果不知道路径是否以文件名或文件夹名结尾,则需要首先检查实际路径以查看该位置是否存在文件/文件夹。在这种情况下,Dan Dimitru的答案可能更合适。

当路径中没有文件名时,我使用此代码片段获取路径的目录:

例如“c:\tmp\test\visual”

输出:

视觉的

试试这个:

string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));

下面的代码仅帮助获取文件夹名称

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
公共ObservableCollection项目=新ObservableCollection(); 尝试 { 字符串[]folderpath=Directory.GetDirectories(stemp); items.Clear(); foreach(FolderPath中的字符串s) { Add(新的gridItems{foldername=s.Remove(0,s.LastIndexOf('\\')+1,folderpath=s}); } } 捕获(例外a) { } 公共类网格项 { 公共字符串foldername{get;set;} 公共字符串folderpath{get;set;} }
这很难看,但避免了分配:

var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();

简单干净。仅使用
System.IO.FileSystem
-效果非常好:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

DirectoryInfo执行剥离目录名的任务

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

还需要注意的是,在循环中获取目录名列表时,
DirectoryInfo
类初始化一次,因此只允许第一次调用。为了绕过此限制,请确保在循环中使用变量来存储任何单个目录的名称

例如,此示例代码循环遍历任何父目录中的目录列表,同时将找到的每个目录名添加到字符串类型的列表中:

[C#]


您是否想要最后一个文件夹名,因此如果您有C:\folder1\folder2\folder3\file.txt,您想要“folder3”?另一个解决方案:返回新的DirectoryInfo(fullPath).name@Davidicardi您的评论真的应该是一个答案,这是值得的。当路径不包含文件(目录路径)时,这不起作用,而@Davidicardi solution包含文件。有趣的是,如果路径是“C:/folder1/folder2./file.txt”(注意folder2末尾的点)结果将是“folder2”,而不是“folder2”。(这是一个完全有效的文件夹名称)警告:此解决方案是错误的!对于“C:/bin/logs”,它返回“bin”。使用returnnewdirectoryinfo(fullPath).Name;相反,您可以只执行Path.GetFileName(dir)操作,它将返回文件夹名称。在这种情况下,文件夹将是
file.txt
,而不是
folder2
,这是更好的答案,因为它实际上返回了OP问题中所问的确切结果。非常感谢。
private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name;  // System32
string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}
Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory
string Folder = Directory.GetParent(path).Name;