枚举文件抛出异常

本文关键字:抛出异常 文件 枚举 | 更新日期: 2023-09-27 18:11:05

我试图枚举通过我的计算机上的文件使用下面的代码,但每次它击中一个文件或目录,我没有权限读取它抛出一个异常。是否有任何方法可以在抛出异常后继续搜索?我知道有些人有类似的问题,但是除了单独检查每个文件/文件夹之外,还有其他方法吗?

try
{
    string[] files = Directory.GetFiles(@"C:'", "*.*",SearchOption.AllDirectories);
    foreach (string file in files)
    {
        Console.WriteLine(file);
    }
}
catch
{
}

谢谢你的帮助,因为这快把我逼疯了!

枚举文件抛出异常

就在今天我遇到了同样的问题。我编写了以下代码。如果您想在实际产品中使用它,您可能需要改进错误处理。因为这是一个一次性脚本,所以我没有太在意。

static IEnumerable<string> EnumerateFilesRecursive(string root,string pattern="*")
{
    var todo = new Queue<string>();
    todo.Enqueue(root);
    while (todo.Count > 0)
    {
        string dir = todo.Dequeue();
        string[] subdirs = new string[0];
        string[] files = new string[0];
        try
        {
            subdirs = Directory.GetDirectories(dir);
            files = Directory.GetFiles(dir, pattern);
        }
        catch (IOException)
        {
        }
        catch (System.UnauthorizedAccessException)
        {
        }
        foreach (string subdir in subdirs)
        {
            todo.Enqueue(subdir);
        }
        foreach (string filename in files)
        {
            yield return filename;
        }
    }
}

可以这样使用:

string[] files = EnumerateFilesRecursive(@"C:'").ToArray();//Note the ToArray()
foreach (string file in files)
{
   Console.WriteLine(file);
}

首先枚举所有文件,将所有文件名存储在内存中,然后才显示它们。或者您可以:

IEnumerable<string> files = EnumerateFilesRecursive(@"C:'");//Note that there is NO ToArray()
foreach (string file in files)
{
   Console.WriteLine(file);
}

它一边写一边枚举,因此不需要同时在内存中保存所有的文件名。

下面是一些基于Windows API的实用程序代码,它枚举文件系统条目而不抛出/捕获异常。

示例用法:

...
foreach (var fi in Utilities.EnumerateFileSystemEntries(@"c:'windows'system32", DirectoryEnumerateOptions.Recursive))
{
    Console.WriteLine(fi.FullName);
}
...

实用工具类:

[Flags]
public enum DirectoryEnumerateOptions
{
    None = 0x0,
    Recursive = 0x1,
    ThrowErrors = 0x2, // if you really want it
    ExpandEnvironmentVariables = 0x4,
}
public static class Utilities
{
    public static IEnumerable<FileSystemInfo> EnumerateFileSystemEntries(string directoryPath, DirectoryEnumerateOptions options = DirectoryEnumerateOptions.None)
    {
        if (directoryPath == null)
            throw new ArgumentNullException(nameof(directoryPath));
        if (!Path.IsPathRooted(directoryPath))
        {
            directoryPath = Path.GetFullPath(directoryPath);
        }
        return EnumerateFileSystemEntriesPrivate(directoryPath, options);
    }
    private static IEnumerable<FileSystemInfo> EnumerateFileSystemEntriesPrivate(string directoryPath, DirectoryEnumerateOptions options = DirectoryEnumerateOptions.None)
    {
        if (!Directory.Exists(directoryPath))
            yield break;
        var findPath = Normalize(directoryPath, options.HasFlag(DirectoryEnumerateOptions.ExpandEnvironmentVariables));
        if (!findPath.EndsWith("*"))
        {
            findPath = Path.Combine(findPath, "*");
        }
        var h = FindFirstFile(findPath, out var data);
        if (h == INVALID_HANDLE_VALUE)
        {
            if (options.HasFlag(DirectoryEnumerateOptions.ThrowErrors))
                throw new Win32Exception(Marshal.GetLastWin32Error());
            yield break;
        }
        if (Include(ref data))
        {
            yield return ToInfo(ref data, directoryPath);
            if (options.HasFlag(DirectoryEnumerateOptions.Recursive) && data.fileAttributes.HasFlag(FileAttributes.Directory))
            {
                foreach (var wfd in EnumerateFileSystemEntriesPrivate(Path.Combine(directoryPath, data.cFileName), options))
                {
                    yield return wfd;
                }
            }
        }
        do
        {
            if (!FindNextFile(h, out data))
            {
                if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_FILES)
                {
                    FindClose(h);
                    break;
                }
                continue;
            }
            if (Include(ref data))
            {
                yield return ToInfo(ref data, directoryPath);
                if (options.HasFlag(DirectoryEnumerateOptions.Recursive) && data.fileAttributes.HasFlag(FileAttributes.Directory))
                {
                    foreach (var wfd in EnumerateFileSystemEntriesPrivate(Path.Combine(directoryPath, data.cFileName), options))
                    {
                        yield return wfd;
                    }
                }
            }
        }
        while (true);
    }
    private static bool Include(ref WIN32_FIND_DATA data) => data.cFileName != "." && data.cFileName != "..";
    private static FileSystemInfo ToInfo(ref WIN32_FIND_DATA data, string directoryPath)
    {
        if (data.fileAttributes.HasFlag(FileAttributes.Directory))
            return new FileInfo(Path.Combine(directoryPath, data.cFileName));
        return new DirectoryInfo(Path.Combine(directoryPath, data.cFileName));
    }
    private static string Normalize(string path, bool expandEnvironmentVariables)
    {
        if (path == null)
            return null;
        string expanded;
        if (expandEnvironmentVariables)
        {
            expanded = Environment.ExpandEnvironmentVariables(path);
        }
        else
        {
            expanded = path;
        }
        if (expanded.StartsWith(_prefix))
            return expanded;
        if (expanded.StartsWith(@"''"))
            return _uncPrefix + expanded.Substring(2);
        return _prefix + expanded;
    }
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
    [DllImport("kernel32", SetLastError = true)]
    private static extern bool FindClose(IntPtr hFindFile);
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
    #pragma warning disable IDE1006 // Naming Styles
    private const int ERROR_NO_MORE_FILES = 18;
    private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
    #pragma warning restore IDE1006 // Naming Styles
    private const string _prefix = @"''?'";
    private const string _uncPrefix = _prefix + @"UNC'";
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    internal struct WIN32_FIND_DATA
    {
        public FileAttributes fileAttributes;
        public uint ftCreationTimeLow;
        public uint ftCreationTimeHigh;
        public uint ftLastAccessTimeLow;
        public uint ftLastAccessTimeHigh;
        public uint ftLastWriteTimeLow;
        public uint ftLastWriteTimeHigh;
        public uint fileSizeHigh;
        public uint fileSizeLow;
        public uint dwReserved0;
        public uint dwReserved1;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string cFileName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
        public string cAlternateFileName;
    }
}