.net core 删除指定路径下的所有文件以及文件夹(文件夹建议保留目录)


1、服务层

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
/// <summary>
/// 删除指定路径下的所有文件
/// </summary>
/// <param name="filepath">指定路径</param>
/// <returns></returns>
public string DeleteSpecifiedPathAllFile(string filepath)
{
try
{
DirectoryInfo info = new DirectoryInfo(filepath);
// 去除文件夹的只读属性
info.Attributes = FileAttributes.Normal & FileAttributes.Directory;
// 去除文件的只读属性
File.SetAttributes(filepath, FileAttributes.Normal);
// 判断文件夹是否存在
if(Directory.Exists(filepath))
{
foreach(var file in Directory.GetFileSystemEntries(filepath))
{
if(File.Exists(file))
{
// 如果有子文件则删除子文件的所有文件
File.Delete(file);
}
else
{
// 循环递归删除子文件夹
DeleteSpecifiedPathAllFile(file);
}
}
// 删除已空文件夹(此步骤会删除指定目录的最底层文件夹,建议保留文件夹目录,此句注释)
// Directory.Delete(filepath, true);
}
return "当前路径下的所有文件夹以及文件删除成功!";
}
catch(Exception ex)
{
return "删除出现异常,异常原因为:" + ex.Message;
}
}

2、接口层

1
2
3
4
5
6
/// <summary>
/// 删除指定路径下的所有文件
/// </summary>
/// <param name="filepath">指定路径</param>
/// <returns></returns>
public string DeleteSpecifiedPathAllFile(string filepath);

3、控制层

1
2
3
4
5
6
7
8
9
10
/// <summary>
/// 删除指定路径下的所有文件
/// </summary>
/// <param name="filepath">指定路径</param>
/// <returns></returns>
[HttpPost, HttpOptions]
public IActionResult DeleteSpecifiedPathAllFile(string filepath)
{
return ToJsonContent(服务名.DeleteSpecifiedPathAllFile(filepath));
}

评论
  目录