How to delete a given directory recursively in C# ? A directory containing files.
Should the System.IO.Directory.Delete with the second parameter true
do the trick?
EDIT:
So, I actually did answer my own question, although the answers here were a little more clarifying. The reason for me asking this in the first place was that the code that has exactly that invocation of Delete
(2nd param set to true
) was not doing what it was supposed to be doing. As it turned out the cause of that was that there was a file somewhere down in the the directory hierarchy with RO
attribute set, and the Polish version of Windows XP
was throwing a really strange message for that.
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.
To delete files recursively means to delete the contents of the folder before deleting the folder itself. If the folder has other folders in it, it will do the same with those folders. Basically it means delete whatever is inside the folder I am deleting, so that I can delete the folder itself.
You use the rm command to delete files and directories in Linux. For directories, this command can be used to delete a directory entirely – that is, it deletes a directory and all files and subdirectories within the directory.
To remove a directory that is not empty, use the rm command with the -r option for recursive deletion. Be very careful with this command, because using the rm -r command will delete not only everything in the named directory, but also everything in its subdirectories.
The only solution that worked for me if the subdirectories also contains files is by using a recursive function:
public static void RecursiveDelete(DirectoryInfo baseDir) { if (!baseDir.Exists) return; foreach (var dir in baseDir.EnumerateDirectories()) { RecursiveDelete(dir); } baseDir.Delete(true); }
It appears that Directory.Delete(dir, true) only delete files of the current directory, and subdirectories if they are empty.
Hope it helps someone.
btw, example: RecursiveDelete( new DirectoryInfo(@"C:\my_dir") );
Yup, that's the point of that parameter. Did you try it and have any problems? (I've just double-checked, and it works fine for me.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With