C# 检查目录是否没有文件,但可能包含子文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11071592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:22:22  来源:igfitidea点击:

Check to see if directory has no files, but it may contain subfolders

c#

提问by Tharkis

I need to check to see if a directory is empty. The problem is, I want to consider the directory empty if it contains a sub folder regardless of whether or not the sub folder contains files. I only care about files in the path I am looking at. This directory will be accessed across the network, which kind of complicates things a bit. What would be the best way to go about this?

我需要检查目录是否为空。问题是,如果目录包含子文件夹,无论子文件夹是否包含文件,我都想将目录视为空。我只关心我正在查看的路径中的文件。该目录将通过网络访问,这使事情有点复杂。解决这个问题的最佳方法是什么?

采纳答案by Douglas

The Directory.EnumerateFiles(string)method overload only returns files contained directlywithin the specified directory. It does not return any subdirectories or files contained therein.

Directory.EnumerateFiles(string)方法重载只返回文件包含直接指定的目录中。它不返回其中包含的任何子目录或文件。

bool isEmpty = !Directory.EnumerateFiles(path).Any();

The advantage of EnumerateFilesover GetFilesis that the collection of files is enumerated on-demand, meaning that the query will succeed as soon as the first file is returned (thereby avoiding reading the rest of the files in the directory).

EnumerateFilesover的优点GetFiles是文件集合是按需枚举的,这意味着只要返回第一个文件,查询就会成功(从而避免读取目录中的其余文件)。

回答by ispiro

Perhaps this:

也许这个:

if (Directory.GetFiles(path).Length == 0)...... ;