Saturday, 26 January 2013

Delete a Directory or Folder in C#

Delete a Directory or Folder in C#



Deleting a   folder/Directory in C# Can be done by 2 ways.
1.Static Method of Directory class Delete
2.Instance method of DirectoryInfo Delete

Before that Call  using System.IO;

Calling

DeleteDirectory(@"c:\personal");

 

Method1   - Directory Static method 

static void DeleteFolder(String src)
 {
     try
     {
        //true means all sub directories with content will be deleted
        //false : Only Empty Directory will be deleted.
        // false: If directory has content recursion set to false exception will be thrown
         Directory.Delete(src,true);

     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

 

Method 2 - DirectoryInfo Instance Method

 static void DeleteFolder(String src)
 {
     try
     {
        //true means all sub directories with content will be deleted
        //false : Only Empty Directory will be deleted.
        // false: If directory has content recursion set to false exception will be thrown

         DirectoryInfo dInfo = new DirectoryInfo(src);
         dInfo.Delete(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

 

 

  • Could not find a part of the path 'c:\mypersonal'. If directory mypersonal does not exists.
  • The directory is not empty.  if directory has files/folders and recursion set to false.

Tags: Delete directory in C#,Delete Folder in C#, Delete all files and folders in C#, Directory.Delete,DirectoryInfo.Delete,System.IO. Delete Directory with files,Delete Directory with content C#,Delete Directory recursively.

No comments:

Post a Comment