C# 如果路径等于文件夹名称,如何检查条件?
Path=c:\users\source\reports\projects\文件 如何检查文件夹名==报告中的项目文件夹 例如: 如果报告 ..…执行一个条件您可以使用System.IO.Path类中的GetDirectory和Filename方法,如下所示:C# 如果路径等于文件夹名称,如何检查条件?,c#,file,path,C#,File,Path,Path=c:\users\source\reports\projects\文件 如何检查文件夹名==报告中的项目文件夹 例如: 如果报告 ..…执行一个条件您可以使用System.IO.Path类中的GetDirectory和Filename方法,如下所示: string path = @"c:\users\source\reports\projects\.file"; string parent = Path.GetDirectory(path); // parent == "@"c:\u
string path = @"c:\users\source\reports\projects\.file";
string parent = Path.GetDirectory(path);
// parent == "@"c:\users\source\reports\projects"
string grandparent = Path.GetDirectory(parent);
// grandparent == "@"c:\users\source\reports"
string filename = Path.Filename(grandparent);
// filename == "reports"
现在您可以检查文件名是否为reports。一种方法是使用该类,该类可以用路径字符串实例化。此类具有表示目录(包括父目录)的属性,该目录返回父文件夹的新DirectoryInfo。它还有一个Name属性,它是文件夹的名称,不能与FullName混淆,FullName是文件夹的完整路径,我们不需要它
因此,在您的示例中,我们需要将名称与父级的父级进行比较,然后将名称与报告进行比较:
如果你想做一个更详细的搜索,比如第一个父项叫做projects,你也可以这样做。这还显示了如何进行不区分大小写的比较,这可能是一个好主意:
var path = @"c:\users\source\reports\projects\FileName.ext";
var dirInfo = new DirectoryInfo(path);
if (dirInfo.Parent.Name.Equals("projects", StringComparison.OrdinalIgnoreCase) &&
dirInfo.Parent.Parent.Name.Equals("reports", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("The file is in 'projects', which is in the 'reports' folder.");
}
var path = @"c:\users\source\reports\projects\FileName.ext";
var dirInfo = new DirectoryInfo(path);
if (dirInfo.Parent.Name.Equals("projects", StringComparison.OrdinalIgnoreCase) &&
dirInfo.Parent.Parent.Name.Equals("reports", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("The file is in 'projects', which is in the 'reports' folder.");
}