c#计算文件夹中的文件数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16193126/
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-10 00:19:04  来源:igfitidea点击:

Counting the number of files in a folder in c#

c#

提问by user1920798

I am a newbie to programming and need help to create a windows application in C# to count the number of files in a folder.

我是编程新手,需要帮助来用 C# 创建 Windows 应用程序来计算文件夹中的文件数。

What method would I use to make it count?

我会用什么方法来计算?

**Update 02/01/2016

**更新 02/01/2016

Exactly what it says, the amunt of files contained inside the folder.

正是它所说的,文件夹中包含的文件数量。

e.g. If a folder contains 3 image files and 3 text files then the application should return the value 6.

例如,如果一个文件夹包含 3 个图像文件和 3 个文本文件,则应用程序应返回值 6。

回答by Hossein Narimani Rad

You can use the System.IO.DirectoryInfo;

您可以使用System.IO.DirectoryInfo;

DirectoryInfo info = new DirectoryInfo(your folder path);
info.GetFiles().Count();

Or as suggested:

或者按照建议:

info.EnumerateFiles();

回答by Yuck

Try this:

尝试这个:

var files = Directory.GetFiles(@"C:\SomeFolder").Length;

Be aware that if the directory doesn't exist this will throw an exception.

请注意,如果目录不存在,这将引发异常。

回答by Hikiko

The DirectoryInfoclass will help you.

DirectoryInfo课程将帮助你。

var info = new DirectoryInfo("D:\");
var files = info.GetFiles();
var dirs = info.GetDirectories();
files.Length;
dirs.Length;

回答by Obama

// This searches in the current directory and also sub directories
int folderCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
// This searches only in the current directory
int folderCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length;

Good luck!

祝你好运!

回答by Pavel Vladov

You should use the Directory.GetFilesmethod.

您应该使用Directory.GetFiles方法。

int fileCount = Directory.GetFiles(@"C:\MyFolder").Length;

If you want to search the subdirectories, too, you can use the following code:

如果您也想搜索子目录,可以使用以下代码:

int fileCount = Directory.GetFiles(@"c:\MyDir\", "*.*", SearchOption.AllDirectories).Length;

Note that if the directory does not exist a DirectoryNotFoundExceptionwill be thrown, so if you are not sure whether the directory exists or not you can either use a try ... catch block or check if the directory exists using the Directory.Exists method:

请注意,如果目录不存在,将抛出DirectoryNotFoundException,因此如果您不确定目录是否存在,您可以使用 try ... catch 块或使用Directory.Exists 方法检查目录是否存在:

if (Directory.Exists(dirName))
{
    // Your code here
}