string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
string path = "C:\folder1\folder2\file.txt";
我可以使用什么对象或方法来给我结果文件夹2?
当前回答
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
其他回答
另一种方法是分割路径,使用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
下面的代码只帮助获取文件夹名称
public ObservableCollection items = new ObservableCollection(); try { string[] folderPaths = Directory.GetDirectories(stemp); items.Clear(); foreach (string s in folderPaths) { items.Add(new gridItems { foldername = s.Remove(0, s.LastIndexOf('\\') + 1), folderpath = s }); } } catch (Exception a) { } public class gridItems { public string foldername { get; set; } public string folderpath { get; set; } }
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
我可能会使用这样的东西:
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
对GetDirectoryName的内部调用将返回完整的路径,而对GetFileName()的外部调用将返回最后一个路径组件——这将是文件夹名。
无论路径是否实际存在,这种方法都有效。然而,这种方法依赖于最初以文件名结尾的路径。如果不知道路径是否以文件名或文件夹名结束,那么它要求您首先检查实际路径,以查看该位置是否存在文件/文件夹。在这种情况下,丹·迪米特鲁的回答可能更合适。
简单干净。只使用System.IO.FileSystem -就像一个魅力:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;