How to recursively delete a directory in .NET that contains files

D

Dave

Directory.Delete(path, true (recursive)) throws an exception of the
directory is not empty. silly as they could have overloaded the
method further providing for deletions with files...

anyway, i also tried using Process and spawning a DOS rmdir command
but that it quite inelegant.

any ideas as to how to cleanly do this?

thanks, dave
 
M

Marc Gravell

any ideas as to how to cleanly do this?
Delete the files and subdirs first? Not tidy, I know... but there
t'is.

Marc
 
A

Alberto Poblacion

Dave said:
Directory.Delete(path, true (recursive)) throws an exception of the
directory is not empty. silly as they could have overloaded the
method further providing for deletions with files...

anyway, i also tried using Process and spawning a DOS rmdir command
but that it quite inelegant.

any ideas as to how to cleanly do this?


private static void BorrarRecursivamente(string ruta)
{
string[] ficheros = Directory.GetFiles(ruta);
foreach (string fichero in ficheros) File.Delete(fichero);
string[] directorios = Directory.GetDirectories(ruta);
foreach (string directorio in directorios)
{
BorrarRecursivamente(directorio);
}
Directory.Delete(ruta);
}
 
W

Willy Denoyette [MVP]

Dave said:
Directory.Delete(path, true (recursive)) throws an exception of the
directory is not empty. silly as they could have overloaded the
method further providing for deletions with files...

anyway, i also tried using Process and spawning a DOS rmdir command
but that it quite inelegant.

any ideas as to how to cleanly do this?

thanks, dave



Easy and fast using System.Management.

string dirName = @"c:\\somefolder";
string objPath = string.Format("Win32_Directory.Name='{0}'",dirName);
using (ManagementObject dir= new ManagementObject(objPath))
{
ManagementBaseObject outParams = dir.InvokeMethod("Delete", null, null);
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if(ret == 0)
Console.WriteLine("Success");
else Console.WriteLine("Failed with error code: {0}", ret);
}


Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top