Click here to Skip to main content
15,881,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Frnds,

I want to delete directory using C#.
I tried this,

C#
Directory.Delete("DirectoryName");


Its working but it deletes only the empty directory.

Also i tried,
C#
public static void Empty(this System.IO.DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}


But the directory contains 100's files. Its taking too much time.

So i want to delete the directory containing files without looping.

Your earlier reply will be helpful!!!


Thanks,
Karthik.J
Posted

You can use

Directory.Delete( "DirectoryName",true );
 
Share this answer
 
Comments
[no name] 21-Nov-12 3:43am    
My 5!
Go with this,
C#
public static void DeleteDirectory(string target_dir)
   {
       string[] files = Directory.GetFiles(target_dir);
       string[] dirs = Directory.GetDirectories(target_dir);

       foreach (string file in files)
       {
           File.SetAttributes(file, FileAttributes.Normal);
           File.Delete(file);
       }

       foreach (string dir in dirs)
       {
           DeleteDirectory(dir);
       }

       Directory.Delete(target_dir, false);
   }
 
Share this answer
 
Comments
[no name] 21-Nov-12 3:25am    
I need to do this without looping, bcoz i having more than 1000 files in that folder.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900