Skip to main content
 首页 » 编程设计

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

2024年12月31日19lonelyxmas

我刚刚关注了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); 
}  

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