嗨,有没有办法从路径中提取第一个目录名称,然后显示到文本框中。像C:\1stFolder\2nFolder\3rdFolder,那么我想在文本框中显示1stFolder
我有一个代码,只显示当前选定的文件夹。
textBox5.Text = new DirectoryInfo(FBD.SelectedPath).Name;
DirectoryInfo di = new DirectoryInfo(@"C:1stFolder2nFolder3rdFolder");
while(di.Parent != null && di.Parent.Parent != null)
{
di = di.Parent;
}
string firstFolderName = di.Name;
**根据下面的评论更新了答案**
试试这个:
void Main()
{
var dir = @"C:1stFolder2nFolder3rdFolder";
DirectoryInfo info = new System.IO.DirectoryInfo(dir);
var root = Directory.GetDirectoryRoot(dir);
while (root != info.Parent.FullName)
{
info = System.IO.Directory.GetParent(info.FullName);
}
Console.WriteLine(info.FullName);
}
为什么不尝试一些简单的
using System.Linq;
var path = "c:pathtosomething";
var firstDirectory = path.Split("\").Skip(1).FirstOrDefault();
甚至
var firstDirectory = path.Split("\")[1];