Using C#, how can I delete all files and folders from a directory, but still keep the root directory?
Using C#, how can I delete all files and folders from a directory, but still keep the root directory?
I used
Directory.GetFiles(picturePath).ToList().ForEach(File.Delete);
for delete the old picture and I don't need any object in this folder
Here is the tool I ended with after reading all posts. It does
It deals with
It doesn't use Directory.Delete because the process is aborted on 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;
}
I know this is an ancient question but this is the (perhaps new) correct answer:
new DirectoryInfo(folder).Delete(true);
Directory.CreateDirectory(folder);
Deletes all recursive and then recreates the folder.
PS - Must have reference using System.IO;
DirectoryInfo.GetFileSystemInfos returns both files and directories :-
new DirectoryInfo(targetDir).GetFileSystemInfos().ToList().ForEach(x => x.Delete());
or if you want to recursive delete :-
new DirectoryInfo(targetDir).GetFileSystemInfos().ToList().ForEach(x =>
{
if (x is DirectoryInfo di)
di.Delete(true);
else
x.Delete();
});