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

简介: 1、服务层```csharp/// <summary>/// 删除指定路径下的所有文件/// </summary>/// <param name="filepath">指定路径</param>/// <returns></returns>public string DeleteSpecifiedPathAllFile(string filepath){ try { DirectoryInfo info = new DirectoryInfo(filepath); // 去除文件夹的只读属性 info.Attribu

1、服务层

/// <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、接口层

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

3、控制层

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

以上就是.net core 删除指定路径下的所有文件以及文件夹(文件夹建议保留目录)的介绍,做此记录,如有帮助,欢迎点赞关注收藏!

目录
相关文章
|
20小时前
|
开发框架 .NET API
ASP.NET Core Web中使用AutoMapper进行对象映射
ASP.NET Core Web中使用AutoMapper进行对象映射
|
1天前
|
存储 开发框架 缓存
【.NET Core】你真的了解HttpRuntime类吗
【.NET Core】你真的了解HttpRuntime类吗
3 0
|
1天前
|
前端开发 C#
【.NET Core】你认识Attribute之CallerMemberName、CallerFilePath、CallerLineNumber三兄弟
【.NET Core】你认识Attribute之CallerMemberName、CallerFilePath、CallerLineNumber三兄弟
3 0
|
1天前
|
安全 C#
【.NET Core】深入理解IO - 读取器和编写器
【.NET Core】深入理解IO - 读取器和编写器
19 5
|
1天前
|
存储 网络协议 程序员
【.NET Core】.NET中的流(Stream)
【.NET Core】.NET中的流(Stream)
20 7
|
1天前
|
存储 缓存 数据安全/隐私保护
【.NET Core】深入理解IO - FileSteam流
【.NET Core】深入理解IO - FileSteam流
16 2
|
1天前
|
存储 Unix C#
【.NET Core】深入理解IO之Path
【.NET Core】深入理解IO之Path
24 2
|
1天前
|
存储 Go C#
【.NET Core】深入理解IO之File类
【.NET Core】深入理解IO之File类
26 6
|
1天前
|
存储 安全 Unix
【.Net Core】深入理解IO之文件和目录
【.Net Core】深入理解IO之文件和目录
22 4