快速I/O,检查目录是否包含文件 [英] Fast I/O to check if directory contains files

查看:48
本文介绍了快速I/O,检查目录是否包含文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用.NET 4编写一个C#应用程序,以从目录列表中读取和处理数据文件(* .dat).

I'm writing a C# application with .NET 4 to read and process data files (*.dat) from a list of directories.

当前,我正在使用以下功能检查目录中是否包含文件:

Currently, I'm checking if a directory contains files using the following function:

    private bool FilesPresent()
    {
        string[] DIRS = Directory.GetDirectories(dataFileDirectoryPath, "*.*", SearchOption.TopDirectoryOnly);
        foreach (string d in DIRS)
        {
            string[] FILES = Directory.GetFiles(d, "*.*", SearchOption.AllDirectories);
            if (FILES.Length > 0) { return true; }
        }
        return false;                
    }

我还尝试了以下帖子中的一些替代解决方案:

I've also tried some alternative solutions from the following post: How to quickly check if folder is empty (.NET)?

重要的是要注意某些目录中的文件超过1,000,000.甚至将数百万个文件名读入一个字符串[]中也要花费很长时间.

It's important to note that some of the directories have in excess of 1,000,000 files. Even reading the million+ file names into a string[] is taking a long time.

我该如何以不同的方式实现它,以使其运行更快?

How can I implement this differently so that it runs faster?

简单地放入;我只想知道检查目录是否为空的最快方法.我现在不关心检索文件名.

Putting it simply; I'd just like to know the fastest way of checking if the directory is not empty. I'm not concerned with retrieving the filenames at this time.

推荐答案

这是使用LINQ和 EnumerateFileSystemEntries + AllDirectories 的另一种方法:

Here's another approach using LINQ and EnumerateFileSystemEntries+AllDirectories:

bool noFiles = !Directory.EnumerateFileSystemEntries(dataFileDirectoryPath, "*.*", SearchOption.AllDirectories)
    .Any(entry => !File.GetAttributes(entry).HasFlag(FileAttributes.Directory));

如果 FileAttribute.HasFlag(FileAttributes.Directory)返回 false ,则它是文件.

If FileAttribute.HasFlag(FileAttributes.Directory) returns false it is a file.

这篇关于快速I/O,检查目录是否包含文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆