我需要一份c#代码,他的功能是获取文件夹以及子文件夹内所有文件全路径的列表
以下是一份C#代码,可以获取指定文件夹以及其子文件夹内的所有文件的全路径列表:
using System;
using System.IO;
using System.Collections.Generic;
namespace FileLister
{
class Program
{
static void Main(string[] args)
{
string folderPath = "C:\\Users\\UserName\\Documents\\TestFolder"; // 替换为需要获取文件列表的文件夹路径
List<string> fileList = GetFileList(folderPath);
foreach (string file in fileList)
{
Console.WriteLine(file);
}
}
static List<string> GetFileList(string folderPath)
{
List<string> fileList = new List<string>();
try
{
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
fileList.Add(file);
}
string[] subFolders = Directory.GetDirectories(folderPath);
foreach (string subFolder in subFolders)
{
List<string> subFolderFiles = GetFileList(subFolder);
fileList.AddRange(subFolderFiles);
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
return fileList;
}
}
}
在上述代码中,我们定义了一个 GetFileList 方法,该方法使用递归的方式获取指定文件夹以及其子文件夹内的所有文件的全路径列表。在主函数中,我们调用 GetFileList 方法,并遍历输出获取到的文件列表。
原文地址: https://www.cveoy.top/t/topic/zZK 著作权归作者所有。请勿转载和采集!