schangxiang@126.com
2025-05-20 3a61cb05bd4339b89127b15c489ae76370905404
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
using GenerateCode_GEBrilliantFactory;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenerateCode_GEBrilliantFactory
{
    public class FileHelper
    {
 
        public static void DeleteAllContentsInFolder(string folderPath)
        {
            try
            {
                if (Directory.Exists(folderPath))
                {
                    // 删除所有文件和子文件夹(包括子文件夹中的文件)
                    foreach (string file in Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories))
                    {
                        File.Delete(file);
                        Console.WriteLine($"已删除文件: {file}");
                    }
 
                    // 删除所有子文件夹(此时文件夹已空,可以安全删除)
                    foreach (string dir in Directory.GetDirectories(folderPath, "*", SearchOption.AllDirectories))
                    {
                        Directory.Delete(dir); // 不需要递归,因为文件已被删除
                        Console.WriteLine($"已删除文件夹: {dir}");
                    }
 
                    Console.WriteLine($"成功清空文件夹 '{folderPath}' 下的所有内容。");
                }
                else
                {
                    Console.WriteLine($"文件夹不存在: {folderPath}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除文件/文件夹时出错: {ex.Message}");
            }
        }
 
 
        public static void ClearFolder(string folderPath)
        {
            try
            {
                if (Directory.Exists(folderPath))
                {
                    // 删除所有文件和子文件夹(包括子文件夹中的文件)
                    Directory.Delete(folderPath, true); // true 表示递归删除
                    Directory.CreateDirectory(folderPath); // 重新创建空文件夹
                    Console.WriteLine($"已清空并重建文件夹 '{folderPath}'。");
                }
                else
                {
                    Console.WriteLine($"文件夹不存在: {folderPath}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空文件夹时出错: {ex.Message}");
            }
        }
    }
}