我正在创建一个在文件中找到重复的应用程序。当我搜索如下文件时:
try
{
string[] allFiles = Directory.GetFiles(
directoryPath, "*.*", SearchOption.AllDirectories
);
for (int i = 0; i < allFiles.Length; i++)
{
//decisions
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
它说
访问路径'C:\ $ Recycle.Bin .......'被拒绝。
我想如果文件夹不可访问,那么移到下一个文件夹,但程序的执行在Directory.GetFiles
方法停止。
答案 0 :(得分:4)
这是一个可以工作的课程:
public static class FileDirectorySearcher
{
public static IEnumerable<string> Search(string searchPath, string searchPattern)
{
IEnumerable<string> files = GetFileSystemEntries(searchPath, searchPattern);
foreach (string file in files)
{
yield return file;
}
IEnumerable<string> directories = GetDirectories(searchPath);
foreach (string directory in directories)
{
files = Search(directory, searchPattern);
foreach (string file in files)
{
yield return file;
}
}
}
private static IEnumerable<string> GetDirectories(string directory)
{
IEnumerable<string> subDirectories = null;
try
{
subDirectories = Directory.EnumerateDirectories(directory, "*.*", SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (subDirectories != null)
{
foreach (string subDirectory in subDirectories)
{
yield return subDirectory;
}
}
}
private static IEnumerable<string> GetFileSystemEntries(string directory, string searchPattern)
{
IEnumerable<string> files = null;
try
{
files = Directory.EnumerateFileSystemEntries(directory, searchPattern, SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (files != null)
{
foreach (string file in files)
{
yield return file;
}
}
}
}
您可以像这样使用它:
IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(@"C:\", "*.txt");
foreach (string fileOrDirectory in filesOrDirectories)
{
// Do something here.
}
它是递归的,但是使用yield会使内存占用空间很小(在我的测试中不到10KB)。如果您只想要与模式匹配的文件而不是目录,只需将EnumerateFileSystemEntries
替换为EnumerateFiles
。