I lifted some code to compare two directories, and it all works fine, but I wanted to improve it for my purposes so I can recycle the code for slightly different requirements. The original code listed all directories, but I wanted to add in a switch so I could decide whether to list all directories or the top level only. Here is a snippet from my code;
public void DoCompare(string pathA, string pathB, bool allDirs)
{
DirectoryInfo dir1 = new DirectoryInfo(pathA);
DirectoryInfo dir2 = new DirectoryInfo(pathB);
if (allDirs)
{
IEnumerable<FileInfo> list1 = dir1.GetFiles("*.*", SearchOption.AllDirectories);
IEnumerable<FileInfo> list2 = dir2.GetFiles("*.*", SearchOption.AllDirectories);
}
else
{
IEnumerable<FileInfo> list1 = dir1.GetFiles("*.*", SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> list2 = dir2.GetFiles("*.*", SearchOption.TopDirectoryOnly);
}
//A custom file comparer defined later
FileCompare myFileCompare = new FileCompare();
bool areIdentical = list1.SequenceEqual(list2, myFileCompare);
Now without the if (allDirs) this works fine. When I put that in, list1 and list 2 are not visible in the last line of code. The actual error is "The name list1 does not exist in the current context". I tried declaring them outside the if, but that relied on them returning results, which isn't possible without the decision. So how do I make these visible outside the if statement?