c# - 删除文件夹及其内容

标签 c# asp.net-mvc asp.net-mvc-5 delete-file

我刚刚关注了this tutorial删除文件夹及其内容

    public ActionResult Product_Delete()
    {
        string idnumber = "07";

        string path1 = @"~/Content/Essential_Folder/attachments_AR/" + idnumber;

        DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));
        EmptyFolder(attachments_AR);
        Directory.Delete(path1);

        ....
    } 

    private void EmptyFolder(DirectoryInfo directory)
    {

        foreach (FileInfo file in directory.GetFiles())
        {
            file.Delete();
        }

        foreach (DirectoryInfo subdirectory in directory.GetDirectories())
        {
            EmptyFolder(subdirectory);
            subdirectory.Delete();
        }

     }

但是使用这个会删除07文件夹中的所有contnet,但最终不会删除07文件夹。

我在这一行中遇到错误 Directory.Delete(path1);

调试后,我可以看到运行时错误并显示以下消息

Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\Content\Essential_Folder\attachments_AR\07'.

但path1值为~/Content/Essential_Folder/attachments_AR/07

最佳答案

原因是Directory.Delete无法识别路径中的~

您需要使用 Server.MapPath() 将其转换为绝对路径,就像您在此处所做的那样:

DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));

您可能还想将其转换一次,并在两种方法中使用:

public ActionResult Product_Delete()
{
    string idnumber = "07";

    string mappedPath1 = Server.MapPath(@"~/Content/Essential_Folder/attachments_AR/" + idnumber);

    DirectoryInfo attachments_AR = new DirectoryInfo(mappedPath1));
    EmptyFolder(attachments_AR);
    Directory.Delete(mappedPath1);

    ....
} 

顺便说一句,绝对不需要手动删除文件。您可以使用

public ActionResult Product_Delete()
{
    string idnumber = "07";
    string mappedPath = Server.MapPath(@"~/Content/Essential_Folder/attachments_AR/" + idnumber);

    Directory.Delete(mappedPath, true);
} 

这将递归地删除所有文件夹、子文件夹和文件,然后删除目录本身。

关于c# - 删除文件夹及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34195306/

相关文章:

asp.net-mvc - Ninject 请求范围和生成的线程

jquery验证: remove error message from form

c# - WPF + Windows 窗体错误处理

c# - 自定义布局,Xamarin 表单。最佳方法

c# - 尝试插入 schema.table.ID 时出现 ORA-01400

c# - 如何使用 Simple injector、Repository 和 Context - code first

c# - Owin 重启后重新连接 SignalR 客户端,但未发布消息

asp.net-mvc - 带有 ASP.Net Identity 的 ASP.NET MVC5 中的自定义验证和角色提供者

c# - 如何在 C# 中创建键/值对数组?

c# - 一个 MVC 表单上的多个表单,用循环创建,只有第一个提交数据