我正在尝试将模板文件夹与子文件夹与现有目录结构进行比较。我试图递归遍历每个目录中的所有子文件夹。我的代码如下。
public void compareDirectories(DirectoryInfo Templatedir, DirectoryInfo Projectdir)
{
DirectoryInfo[] recursiveTemplatedirs = Templatedir.GetDirectories("*.*");
DirectoryInfo[] recursiveProjectdirs = Projectdir.GetDirectories("*.*");
string recursiveName;
string projectName;
foreach (DirectoryInfo recursiveTemplatedir in recursiveTemplatedirs)
{
recursiveName = recursiveTemplatedir.Name.ToString();
foreach (DirectoryInfo recursiveProjectdir in recursiveProjectdirs)
{
projectName = recursiveProjectdir.Name.ToString();
if (recursiveName == projectName)
{
lstTest.Items.Add("Match " + recursiveName);
}
else lstTest.Items.Add("No Match " + recursiveName);
}
compareDirectories(recursiveTemplatedir, recursiveProjectdir);
}
}
当我尝试运行它时,我得到的错误是recursiveProjectdir在此上下文中不存在。有关如何运行的任何想法?
答案 0 :(得分:3)
您收到错误,因为recursiveProjectdir
的范围仅在foreach loop
foreach (DirectoryInfo recursiveTemplatedir in recursiveTemplatedirs)
{
recursiveName = recursiveTemplatedir.Name.ToString();
foreach (DirectoryInfo recursiveProjectdir in recursiveProjectdirs)
{
}
//recursiveProjectdir doesn't exists outside the foreach loop
compareDirectories(recursiveTemplatedir, recursiveProjectdir);
}
答案 1 :(得分:0)
将最后的compareDirectories移到foreach循环中。刚修改了你的测试方法。
DelegateClass