C#中如何获取文件夹下具体文件的数量
作者:野牛程序员:2023-12-13 15:50:38C#阅读 2739
使用C#中的Directory和File类可以轻松获取文件夹下具体文件的数量。以下是一个简单的示例代码:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "文件夹路径";
int fileCount = GetFileCount(folderPath);
Console.WriteLine($"文件夹中的文件数量为:{fileCount}");
}
static int GetFileCount(string folderPath)
{
try
{
// 检查文件夹是否存在
if (Directory.Exists(folderPath))
{
// 获取文件夹中的文件列表
string[] files = Directory.GetFiles(folderPath);
// 返回文件数量
return files.Length;
}
else
{
// 文件夹不存在
return 0;
}
}
catch (Exception)
{
// 处理异常情况
return -1;
}
}
}这段代码会输出文件夹中文件的数量。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:在Python中什么是构造器?
- 下一篇:在Python中什么是slicing?
