问题描述
我正在创建一个在文件中发现重复的应用程序。当我搜索如下文件:
I am creating an application which finds duplication in files. When I search files like:
try
{
string[] allFiles = Directory.GetFiles(
directoryPath, "*.*", SearchOption.AllDirectories
);
for (int i = 0; i < allFiles.Length; i++)
{
//decisions
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
它说
我想要一个文件夹不可访问,然后移动到下一个但执行程序停止在 Directory.GetFiles
方法。
I want if a folder is not accessible then move to the next but execution of program stops at Directory.GetFiles
method.
推荐答案
这是一个可以工作的类:
Here's a class that will work:
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
。
It's recursive, but the use of yield gives it a low memory footprint (under 10KB in my testing). If you want only files that match the pattern and not directories as well just replace EnumerateFileSystemEntries
with EnumerateFiles
.
这篇关于UnauthorizedAccessException在获取文件时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!