How to quickly check if folder is empty (.NET)?

后端 未结 18 912
旧时难觅i
旧时难觅i 2020-12-02 08:22

I have to check, if directory on disk is empty. It means, that it does not contain any folders/files. I know, that there is a simple method. We get array of FileSystemInfo\'

18条回答
  •  醉酒成梦
    2020-12-02 08:36

    There is a new feature in Directory and DirectoryInfo in .NET 4 that allows them to return an IEnumerable instead of an array, and start returning results before reading all the directory contents.

    • What's New in the BCL in .NET 4 Beta 1
    • Directory.EnumerateFileSystemEntries method overloads
    public bool IsDirectoryEmpty(string path)
    {
        IEnumerable items = Directory.EnumerateFileSystemEntries(path);
        using (IEnumerator en = items.GetEnumerator())
        {
            return !en.MoveNext();
        }
    }
    

    EDIT: seeing that answer again, I realize this code can be made much simpler...

    public bool IsDirectoryEmpty(string path)
    {
        return !Directory.EnumerateFileSystemEntries(path).Any();
    }
    

提交回复
热议问题