您可以使用FileInfo和DirectoryInfo类。
执行从右到左的搜索,如下所示:
var fi = new FileInfo(""\\Tests\Results\knowles\project\LU\D15\RUN1\Results.xml"");
var di = fi.Directory;
var find = "project";
while (di.Name.ToLower() != find.ToLower() && di != null)
{
di = di.Parent;
}
if (di == null)
{
throw new Exception(string.Format("Directory with name '{0}' was not found.", find));
}
使用递归解决方案进行从左到右的搜索。像这样的东西:
注意这是未经测试的,所以可能不完全正确,但我认为这通常是您想要实现的目标。
var fi = new FileInfo(""\\Tests\Results\knowles\project\LU\D15\RUN1\Results.xml"");
var di = fi.Directory;
var find = "project";
di = GetGreatestParent(di, find);
if (di == null)
{
throw new Exception(string.Format("Directory with name '{0}' was not found.", find));
}
public DirectoryInfo GetGreatestParent(DirectoryInfo Dir, string Find)
{
if (Dir != null)
{
var p = GetGreatestParent(Dir.Parent, string Find);
if (p != null)
{
return p;
}
else if (Dir.Name.ToLower() == Find.ToLower())
{
return Dir;
}
}
return null;
}