c#获取文件夹下的所有文件名
作者:野牛程序员:2023-07-29 08:30:02C#阅读 3886
在 C# 中,可以使用 Directory.GetFiles() 方法来获取文件夹下的所有文件名。此方法会返回一个包含指定文件夹中所有文件的字符串数组,可以遍历该数组来获取文件名。
以下是一个示例代码,演示如何使用 C# 获取文件夹下的所有文件名:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = @"C:\\YourFolderPath"; // 替换为你的文件夹路径
try
{
string[] fileNames = Directory.GetFiles(folderPath);
Console.WriteLine("文件夹 " + folderPath + " 下的文件名:");
foreach (string fileName in fileNames)
{
Console.WriteLine(Path.GetFileName(fileName));
}
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("找不到文件夹:" + folderPath);
}
catch (Exception ex)
{
Console.WriteLine("发生错误:" + ex.Message);
}
}
}在上述代码中,使用 Directory.GetFiles() 方法来获取指定文件夹(folderPath)下的所有文件名。然后,使用 foreach 循环遍历返回的文件名数组,使用 Path.GetFileName() 方法来获取文件名并输出到控制台。
请确保将 folderPath 替换为希望获取文件名的文件夹路径。运行代码后,它将输出指定文件夹下的所有文件名。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c获取文件夹下的所有文件名
- 下一篇:excel读取文件夹内文件名
