C # delete the folder and all files and folders in this folder

I try to delete a folder and all the files and folders in this folder, I use the following code and get the error Folder is not empty , any suggestions on what I can do?

 try { var dir = new DirectoryInfo(@FolderPath); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(); dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index); } catch (IOException ex) { MessageBox.Show(ex.Message); } 
+69
c # directory
Feb 08 2018-10-10 at
source share
9 answers
 dir.Delete(true); // true => recursive delete 
+119
Feb 08 '10 at 15:46
source share

Read the manual:

Directory.Delete Method (String, Boolean)

 Directory.Delete(folderPath, true); 
+73
Feb 08 '10 at 15:46
source share

Try:

 System.IO.Directory.Delete(path,true) 

This will recursively delete all files and folders under "path" if you have permission to do so.

+20
Feb 08 '10 at 15:47
source share

Err, how about just calling Directory.Delete(path, true); ?

+6
Feb 08 '10 at 15:46
source share

The Directory.Delete method has a recursive logical parameter, it should do what you need

+4
Feb 08 '10 at 15:46
source share

You should use:

 dir.Delete(true); 

to recursively delete the contents of this folder. See MSDN DirectoryInfo.Delete () overload .

+3
Feb 08 '10 at 15:47
source share

Try it.

 namespace EraseJunkFiles { class Program { static void Main(string[] args) { DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\"); foreach (DirectoryInfo dir in yourRootDir.GetDirectories()) DeleteDirectory(dir.FullName, true); } public static void DeleteDirectory(string directoryName, bool checkDirectiryExist) { if (Directory.Exists(directoryName)) Directory.Delete(directoryName, true); else if (checkDirectiryExist) throw new SystemException("Directory you want to delete is not exist"); } } } 
+2
Nov 18 '16 at 3:17
source share
 public void Empty(System.IO.DirectoryInfo directory) { try { logger.DebugFormat("Empty directory {0}", directory.FullName); foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete(); foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); } catch (Exception ex) { ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture)); throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex); } } 
0
Apr 08 '13 at 13:27
source share

Try this:

 foreach (string files in Directory.GetFiles(SourcePath)) { FileInfo fileInfo = new FileInfo(files); fileInfo.Delete(); //delete the files first. } Directory.Delete(SourcePath);// delete the directory as it is empty now. 
0
Jan 30 '19 at 6:28
source share



All Articles