我想循环遍历文件夹中的所有子文件夹和文件,并检查特定文件名是否包含文件夹说" X"在它的路径(祖先)。我不想使用字符串比较。有更好的方法吗?
答案 0 :(得分:0)
您可以使用Directory.GetFiles()
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(@"c:\", "c*");
Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
https://msdn.microsoft.com/en-us/library/6ff71z1w(v=vs.110).aspx
答案 1 :(得分:0)
您可以使用递归搜索,例如
// sourcedir = path where you start searching
public void DirSearch(string sourcedir)
{
try
{
foreach (string dir in Directory.GetDirectories(sourcedir))
{
DirSearch(dir);
}
// If you're looking for folders and not files take Directory.GetDirectories(string, string)
foreach (string filepath in Directory.GetFiles(sourcedir, "whatever-file*wildcard-allowed*"))
{
// list or sth to hold all pathes where a file/folder was found
_internalPath.Add(filepath);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
因此,在您的情况下,您正在寻找文件夹XYZ,请使用
// Takes all folders in sourcedir e.g. C:/ that starts with XYZ
foreach (string filepath in Directory.GetDirectories(sourcedir, "XYZ*")){...}
因此,如果您要提供sourcedir C:/
,它会搜索C:/中可用的所有文件夹,这当然会花费相当长的时间
答案 2 :(得分:0)
回答您的具体问题(问题标题中的问题,而不是正文中的问题),一旦您拥有文件名(其他答案告诉您如何查找),您可以这样做:
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return Path.GetDirectoryName(pathToFileName)
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}
这只适用于绝对路径...如果你有相对路径,你可以进一步复杂化(这需要文件实际存在):
bool PathHasFolder(string pathToFileName, string folderToCheck)
{
return new FileInfo(pathToFileName)
.Directory
.FullName
.Split(Path.DirectorySeparatorChar)
.Any(x => x == folderToCheck);
}