Using C, how can I delete all files and folders from the directory, but still keep the root directory?
29 solutions
657 votes
System.IO.DirectoryInfo di = new DirectoryInfo("YourPath"); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); }
If your directory may contain many files, GetFiles() is more effective than GetDirectories(), because when you use EnumerateFiles(), you can start enumerating the entire collection before returning it, rather than GetFiles(), you need to load the entire collection into memory before enumerating it. See this reference here:
Therefore, EnumerateFiles () can be more effective when you use many files and directories.
This also applies to GetFiles() and GetDirectories(). Therefore, the code will be:
foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.EnumerateDirectories()) { dir.Delete(true); }
For the purpose of this problem, there is no reason to use GetFiles() and GetDirectories().
gsharp answered 2018-12-26T10:24:56Z
162 votes
Yes, this is the right way. If you want to give yourself a "clean" (or, I prefer to call it the "empty" function), you can create an extension method.
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); }
This will allow you to do similar things
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\..."); directory.Empty();
Adam Robinson answered 2018-12-26T10:25:20Z
64 votes
The following code will recursively clear the folder:
private void clearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach(FileInfo fi in dir.GetFiles()) { fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { clearFolder(di.FullName); di.Delete(); } }
hiteshbiblog answered 2018-12-26T10:25:41Z
37 votes
new System.IO.DirectoryInfo(@"C:\Temp").Delete(true); //Or System.IO.Directory.Delete(@"C:\Temp", true);
Thulasiram answered 2018-12-26T10:25:56Z
36 votes
We can also express our love for LINQ:
using System.IO; using System.Linq; ... var directory = Directory.GetParent(TestContext.TestDir); directory.EnumerateFiles() .ToList().ForEach(f => f.Delete()); directory.EnumerateDirectories() .ToList().ForEach(d => d.Delete(true));
Please note that my solution does not meet the requirements because I use Get*().ToList().ForEach(...) to generate the same IEnumerable twice. I use the extension method to avoid this problem:
using System.IO; using System.Linq; ... var directory = Directory.GetParent(TestContext.TestDir); directory.EnumerateFiles() .ForEachInEnumerable(f => f.Delete()); directory.EnumerateDirectories() .ForEachInEnumerable(d => d.Delete(true));
This is the extension method:
/// <summary> /// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>. /// </summary> public static class IEnumerableOfTExtensions { /// <summary> /// Performs the <see cref="System.Action"/> /// on each item in the enumerable object. /// </summary> /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam> /// <param name="enumerable">The enumerable.</param> /// <param name="action">The action.</param> /// <remarks> /// "I am philosophically opposed to providing such a method, for two reasons. /// ...The first reason is that doing so violates the functional programming principles /// that all the other sequence operators are based upon. Clearly the sole purpose of a call /// to this method is to cause side effects." /// —Eric Lippert, "foreach" vs "ForEach" [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx] /// </remarks> public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action) { foreach (var item in enumerable) { action(item); } } }
rasx answered 2018-12-26T10:26:25Z
29 votes
The simplest way:
Directory.Delete(path,true); Directory.CreateDirectory(path);
Note that this may delete some permissions for the folder.
Igor Mukhachev answered 2018-12-26T10:26:51Z
24 votes
Based on hiteshb log, you should probably ensure that the file is readable and writable.
private void ClearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach (FileInfo fi in dir.GetFiles()) { fi.IsReadOnly = false; fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { ClearFolder(di.FullName); di.Delete(); } }
If you know there are no subfolders, this is probably the simplest thing:
Directory.GetFiles(folderName).ForEach(File.Delete)
zumalifeguard answered 2018-12-26T10:27:16Z
12 votes
System.IO.Directory.Delete(installPath, true); System.IO.Directory.CreateDirectory(installPath);
MacGyver answered 2018-12-26T10:27:33Z
6 votes
Every method I tried had a System.IO error in some way. The following methods can confirm that even if the folder is empty, it can be read-only, and so on.
ProcessStartInfo Info = new ProcessStartInfo(); Info.Arguments = "/C rd /s /q \"C:\\MyFolder""; Info.WindowStyle = ProcessWindowStyle.Hidden; Info.CreateNoWindow = true; Info.FileName = "cmd.exe"; Process.Start(Info);
Alexandru Dicu answered 2018-12-26T10:27:56Z
6 votes
The following code clears the directory but keeps the root directory (recursion).
Action<string> DelPath = null; DelPath = p => { Directory.EnumerateFiles(p).ToList().ForEach(File.Delete); Directory.EnumerateDirectories(p).ToList().ForEach(DelPath); Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete); }; DelPath(path);
hofi answered 2018-12-26T10:28:16Z
4 votes
Static methods that use only File and Directory instead of FileInfo and DirectoryInfo will perform faster. (see the answer to accept the difference between File and FileInfo in C?). The answer is shown as a practical method.
public static void Empty(string directory) { foreach(string fileToDelete in System.IO.Directory.GetFiles(directory)) { System.IO.File.Delete(fileToDelete); } foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory)) { System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true); } }
Kriil answered 2018-12-26T10:28:45Z
3 votes
In Windows 7, if you just created it manually using Windows Explorer, the directory structure is similar:
C: \AAA \BBB \CCC \DDD
And run the code suggested in the original problem to clean up the directory C: \ AAA. Line di.Delete(true) always fails due to IOException "directory is not empty" when trying to delete the BBB. This may be due to some kind of latency / cache in Windows Explorer.
The following code works reliably for me:
static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo(@"c:\aaa"); CleanDirectory(di); } private static void CleanDirectory(DirectoryInfo di) { if (di == null) return; foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos()) { CleanDirectory(fsEntry as DirectoryInfo); fsEntry.Delete(); } WaitForDirectoryToBecomeEmpty(di); } private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di) { for (int i = 0; i < 5; i++) { if (di.GetFileSystemInfos().Length == 0) return; Console.WriteLine(di.FullName + i); Thread.Sleep(50 * i); } }
farfareast answered 2018-12-26T10:29:24Z
3 votes
private void ClearFolder(string FolderName) { DirectoryInfo dir = new DirectoryInfo(FolderName); foreach (FileInfo fi in dir.GetFiles()) { fi.IsReadOnly = false; fi.Delete(); } foreach (DirectoryInfo di in dir.GetDirectories()) { ClearFolder(di.FullName); di.Delete(); } }
Mong Zhu answered 2018-12-26T10:29:41Z
2 votes
string directoryPath = "C:\Temp"; Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete); Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);
AVH answered 2018-12-26T10:29:57Z
2 votes
This version does not use recursive calls and solves the readonly problem.
public static void EmptyDirectory(string directory) { // First delete all the files, making sure they are not readonly var stackA = new Stack<DirectoryInfo>(); stackA.Push(new DirectoryInfo(directory)); var stackB = new Stack<DirectoryInfo>(); while (stackA.Any()) { var dir = stackA.Pop(); foreach (var file in dir.GetFiles()) { file.IsReadOnly = false; file.Delete(); } foreach (var subDir in dir.GetDirectories()) { stackA.Push(subDir); stackB.Push(subDir); } } // Then delete the sub directories depth first while (stackB.Any()) { stackB.Pop().Delete(); } }
Jeppe Andreasen answered 2018-12-26T10:30:37Z
2 votes
This is the tool I ended after reading all the posts. Such is the case
- Delete all content that can be deleted
- Returns false if some files are still in the folder
It handles
- Read only file
- Delete delay
- Locked files
It does not use Directory.Delete because the process aborts on an exception.
/// <summary> /// Attempt to empty the folder. Return false if it fails (locked files...). /// </summary> /// <param name="pathName"></param> /// <returns>true on success</returns> public static bool EmptyFolder(string pathName) { bool errors = false; DirectoryInfo dir = new DirectoryInfo(pathName); foreach (FileInfo fi in dir.EnumerateFiles()) { try { fi.IsReadOnly = false; fi.Delete(); //Wait for the item to disapear (avoid 'dir not empty' error). while (fi.Exists) { System.Threading.Thread.Sleep(10); fi.Refresh(); } } catch (IOException e) { Debug.WriteLine(e.Message); errors = true; } } foreach (DirectoryInfo di in dir.EnumerateDirectories()) { try { EmptyFolder(di.FullName); di.Delete(); //Wait for the item to disapear (avoid 'dir not empty' error). while (di.Exists) { System.Threading.Thread.Sleep(10); di.Refresh(); } } catch (IOException e) { Debug.WriteLine(e.Message); errors = true; } } return !errors; }
Eric Bole-Feysot answered 2018-12-26T10:31:29Z
1 votes
Use the GetDirectories method of DirectoryInfo.
foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories()) subDir.Delete(true);
Mr_Hmp answered 2018-12-26T10:31:49Z
1 votes
The following example shows how to do this. It first creates some directories and a file, and then through Directory.Delete(topPath, true); Delete them:
static void Main(string[] args) { string topPath = @"C:\NewDirectory"; string subPath = @"C:\NewDirectory\NewSubDirectory"; try { Directory.CreateDirectory(subPath); using (StreamWriter writer = File.CreateText(subPath + @"\example.txt")) { writer.WriteLine("content added"); } Directory.Delete(topPath, true); bool directoryExists = Directory.Exists(topPath); Console.WriteLine("top-level directory exists: " + directoryExists); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.Message); } }
It comes from[ https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx. ]
Salma Tofaily answered 2018-12-26T10:32:14Z
1 votes
This is not the best way to deal with the above problems. But it's another
while (Directory.GetDirectories(dirpath).Length > 0) { //Delete all files in directory while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0) { File.Delete(Directory.GetFiles(dirpath)[0]); } Directory.Delete(Directory.GetDirectories(dirpath)[0]); }
dsmyrnaios answered 2018-12-26T10:32:44Z
0 votes
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); if (Folder .Exists) { foreach (FileInfo fl in Folder .GetFiles()) { fl.Delete(); } Folder .Delete(); }
Ashok Luhach answered 2018-12-26T10:33:01Z
0 votes
using System; using System.IO; namespace DeleteFoldersAndFilesInDirectory { class Program { public static void DeleteAll(string path) { string[] directories = Directory.GetDirectories(path); string[] files = Directory.GetFiles(path); foreach (string x in directories) Directory.Delete(x, true); foreach (string x in files) File.Delete(x); } static void Main() { Console.WriteLine("Enter The Directory:"); string directory = Console.ReadLine(); Console.WriteLine("Deleting all files and directories ..."); DeleteAll(directory); Console.WriteLine("Deleted"); } } }
Diaa Eddin answered 2018-12-26T10:33:17Z
0 votes
This will show us how to delete the folder and check it. We use the text box
using System.IO; namespace delete_the_folder { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Deletebt_Click(object sender, EventArgs e) { //the first you should write the folder place if (Pathfolder.Text=="") { MessageBox.Show("ples write the path of the folder"); Pathfolder.Select(); //return; } FileAttributes attr = File.GetAttributes(@Pathfolder.Text); if (attr.HasFlag(FileAttributes.Directory)) MessageBox.Show("Its a directory"); else MessageBox.Show("Its a file"); string path = Pathfolder.Text; FileInfo myfileinf = new FileInfo(path); myfileinf.Delete(); } } }
Abdelrhman Khalil answered 2018-12-26T10:34:11Z
0 votes
using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); foreach (string filePath in filePaths) File.Delete(filePath);
SynsMasTer answered 2018-12-26T10:34:26Z
0 votes
From main phone
static void Main(string[] args) { string Filepathe =<Your path> DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName); }
Add this method
public static void DeleteDirectory(string path) { if (Directory.Exists(path)) { //Delete all files from the Directory foreach (string file in Directory.GetFiles(path)) { File.Delete(file); } //Delete all child Directories foreach (string directory in Directory.GetDirectories(path)) { DeleteDirectory(directory); } //Delete a Directory Directory.Delete(path); } }
sansalk answered 2018-12-26T10:34:51Z
0 votes
foreach (string file in System.IO.Directory.GetFiles(path)) { System.IO.File.Delete(file); } foreach (string subDirectory in System.IO.Directory.GetDirectories(path)) { System.IO.Directory.Delete(subDirectory,true); }
Manish Y answered 2018-12-26T10:35:06Z
0 votes
To delete a folder, use the text box and button using System.IO; Code of:
private void Deletebt_Click(object sender, EventArgs e) { System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text); foreach (FileInfo file in myDirInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in myDirInfo.GetDirectories()) { dir.Delete(true); } }
Abdelrhman Khalil answered 2018-12-26T10:35:26Z
-2 votes
private void ClearDirectory(string path) { if (Directory.Exists(path))//if folder exists { Directory.Delete(path, true);//recursive delete (all subdirs, files) } Directory.CreateDirectory(path);//creates empty directory }
dadziu answered 2018-12-26T10:35:42Z
-3 votes
The only thing you should do is set Directory.Delete("C:\MyDummyDirectory", True) to True.
Directory.Delete("C:\MyDummyDirectory", True)
Thanks. NET.:)
LysanderM answered 2018-12-26T10:36:10Z
-4 votes
IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)
You don't need more
Reprint: c - how to delete all files and folders in the directory- ITranslater