Delete directory, if include the root - CSharp File IO

CSharp examples for File IO:Directory

Description

Delete directory, if include the root

Demo Code

//      Copyright (c) 2014 OSky. All rights reserved.
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;//from  w  ww  .j a v  a  2  s . c  o m
using System.Collections.Generic;
using System;

public class Main{
        public static bool Delete(string directory, bool isDeleteRoot = true)
        {
            directory.CheckNotNullOrEmpty("directory");

            bool flag = false;
            DirectoryInfo dirPathInfo = new DirectoryInfo(directory);
            if (dirPathInfo.Exists)
            {
                foreach (FileInfo fileInfo in dirPathInfo.GetFiles())
                {
                    fileInfo.Delete();
                }
                foreach (DirectoryInfo subDirectory in dirPathInfo.GetDirectories())
                {
                    Delete(subDirectory.FullName);
                }
                if (isDeleteRoot)
                {
                    dirPathInfo.Attributes = FileAttributes.Normal;
                    dirPathInfo.Delete();
                }
                flag = true;
            }
            return flag;
        }
}

Related Tutorials