string path = "C:\folder1\folder2\file.txt";

我可以使用什么对象或方法来给我结果文件夹2?


当前回答

试试这个:

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;

其他回答

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

例如“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;

另一种方法是分割路径,使用c# 8.0中引入的Index Struct从路径中获取倒数第二个元素。

var path = @"C:\folder1\folder2\file.txt";
var folder = path.Split(@"\")[^2]; // 2nd element from the end

Console.WriteLine(folder); // folder2

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

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

[C#]

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

(VB。净)

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
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();