I just followed this tutorial to delete a folder and its content
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();
}
}
But using this its deleting all the contnet in 07
folder, but its not deleting the 07
folder finally.
I'm getting error in this line Directory.Delete(path1);
Once I debug I can see run time error with below message
Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\Content\Essential_Folder\attachments_AR\07'.
but path1 value is ~/Content/Essential_Folder/attachments_AR/07
The reason is that Directory.Delete
cannot recognize ~
in the path.
You need to convert it to an absolute path using Server.MapPath()
like you did it here:
DirectoryInfo attachments_AR = new DirectoryInfo(Server.MapPath(path1));
You may also want to convert it once, and use in both methods:
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);
....
}
By the way, there is absolutely no need to remove files manually. You can use
public ActionResult Product_Delete()
{
string idnumber = "07";
string mappedPath = Server.MapPath(@"~/Content/Essential_Folder/attachments_AR/" + idnumber);
Directory.Delete(mappedPath, true);
}
which will remove all folders, subfolders and files recursively, and then will remove directory itself.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments