CSharp examples for System.IO:DirectoryInfo
Attempts to delete each file and subdirectory in . Not guaranteed to succeed, but will not throw an exception
using System.Text; using System.Runtime.InteropServices; using System.IO;// w w w. ja v a 2 s . c om using System; public class Main{ /// <summary> /// Attempts to delete each file and subdirectory in <paramref name="path"/>. Not guaranteed to succeed, but will not throw an exception /// </summary> /// <param name="path"></param> public static void TryDeleteFolderRecursively(string path) { if (!Directory.Exists(path)) return; foreach (string file in Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)) { try { File.Delete(file); } catch { /* carry on */ } } foreach (string directory in Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly)) { TryDeleteFolderRecursively(directory); } try { Directory.Delete(path); } catch { /* carry on */} } }