1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- namespace IES.ExamServer.Helpers
- {
- public class FileHelper
- {
- /// <summary>
- /// 删除整个文件夹及其内容
- /// </summary>
- /// <param name="folderPath"></param>
- /// <returns></returns>
- public static bool DeleteFolder(string folderPath)
- {
- bool result = false;
- try
- {
- if (Directory.Exists(folderPath))
- {
- // 删除文件夹及其所有内容
- Directory.Delete(folderPath, true);
- result = true;
- //Console.WriteLine($"Folder '{folderPath}' deleted successfully.");
- }
- else
- {
- //Console.WriteLine($"Folder '{folderPath}' does not exist.");
- result = true;
- }
- }
- catch (Exception ex)
- {
- result = false;
- //Console.WriteLine($"Error: {ex.Message}");
- }
- return result;
- }
- /// <summary>
- /// 列出文件夹下的所有子文件及子文件夹的子文件
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <param name="filter">获取指定匹配模式的文件,如后缀, local.json</param>
- /// <returns></returns>
- public static List<string> ListAllFiles(string directoryPath, string? filter = null)
- {
- List<string> filePaths = new List<string>();
- DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
- // 获取目录下的所有文件(包括子目录中的文件)
- FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories);
- foreach (FileInfo file in files)
- {
- if (string.IsNullOrWhiteSpace(filter))
- {
- filePaths.Add(file.FullName);
- continue;
- }
- else
- {
- if (file.FullName.Contains(filter))
- {
- filePaths.Add(file.FullName);
- }
- }
- }
- return filePaths;
- }
- }
- }
|