Force Delete folder - CSharp File IO

CSharp examples for File IO:Directory

Description

Force Delete folder

Demo Code


using System.IO;/*  ww  w  . j a  va  2s  .c  o  m*/
using System.Diagnostics.Contracts;

public class Main{
        public static void ForceDelete(string path)
        {
            Contract.Requires(!string.IsNullOrEmpty(path));

            if (!Directory.Exists(path))
            {
                return;
            }

            var baseFolder = new DirectoryInfo(path);

            foreach (var item in baseFolder.EnumerateDirectories("*", SearchOption.AllDirectories))
            {
                item.Attributes = ResetAttributes(item.Attributes);
            }

            foreach (var item in baseFolder.EnumerateFiles("*", SearchOption.AllDirectories))
            {
                item.Attributes = ResetAttributes(item.Attributes);
            }

            baseFolder.Delete(true);
        }
        private static FileAttributes ResetAttributes(FileAttributes attributes)
        {
            return attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
        }
}

Related Tutorials