Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete folder/files and subfolder

Tags:

c#

I want to delete a folder containing files and a subfolder, also containing files. I have used everything, but it is not working for me. I'm using the following function in my web-application asp.net:

var dir = new DirectoryInfo(folder_path);
dir.Delete(true); 

Sometimes it deletes a folder, or sometimes it doesn't. If a subfolder contains a file, it only deletes the file, and not the folder as well.

like image 533
safi Avatar asked Feb 23 '11 15:02

safi


People also ask

How do I delete a folder and subfolder?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

What is the difference between delete and delete subfolders and files?

Delete Subfolders and Files: Allows or denies deleting subfolders and files, even if the Delete permission has not been granted on the subfolder or file. (Applies to folders.) Delete: Allows or denies deleting the file or folder.

How do I delete files and subfolders in cmd?

Run the command RMDIR /Q/S foldername to delete the folder and all of its subfolders.

How do I delete a folder and a file in a folder?

You can delete multiple files or folders by holding down the Ctrl key and clicking each file or folder before pressing Delete . You can hold down the Shift key while pressing the Delete key to prevent files from going to the Recycle Bin when deleted.


2 Answers

Directory.Delete(folder_path, recursive: true);

would also get you the desired result and a lot easier to catch errors.

like image 136
Leon Avatar answered Oct 17 '22 23:10

Leon


This looks about right: http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html

//to call the below method
EmptyFolder(new DirectoryInfo(@"C:\your Path"))


using System.IO; // dont forget to use this header

//Method to delete all files in the folder and subfolders

private void EmptyFolder(DirectoryInfo directoryInfo)
{
    foreach (FileInfo file in directoryInfo.GetFiles())
    {       
       file.Delete();
     }

    foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
    {
      EmptyFolder(subfolder);
    }
}
like image 43
Phil C Avatar answered Oct 17 '22 23:10

Phil C