#region Using
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace Wankuma.IO
{
public static partial class Directory
{
#region public static void DeleteRecursion(string path)
///
/// ディレクトリを再帰的に削除します。
/// System.IO.Directory.Deleteと違うのはリードオンリーファイルも削除します。
/// また特殊フォルダ、ルートフォルダは削除できません。
///
/// 削除対象のフォルダパス
public static void DeleteRecursion(string path)
{
//スペシャルフォルダの列挙子配列を取得する
System.Environment.SpecialFolder[] Values = (System.Environment.SpecialFolder[])Enum.GetValues(typeof(System.Environment.SpecialFolder));
//特殊フォルダそのものでないか確認する。
Array.ForEach(Values, delegate(System.Environment.SpecialFolder folder)
{
string SpecialPath = System.Environment.GetFolderPath(folder);
if ( SpecialPath == path )
{
throw new UnauthorizedAccessException(string.Format("特殊フォルダは削除できません。{0}", folder.ToString()));
}
});
//ドライブのルートもチェックを行う
if (System.IO.Path.GetPathRoot(path) == path)
{
throw new UnauthorizedAccessException(string.Format("ルートフォルダは削除できません。{0}", path));
}
//実際の削除処理を行う
DeleteRecursionNoCheck(path);
}
#endregion
///
/// ディレクトリを再帰的に削除します。
/// System.IO.Directory.Deleteと違うのはリードオンリーファイルも削除します。
///
/// 削除対象のフォルダパス
public static void DeleteRecursionNoCheck(string path)
{
//指定フォルダは以下に存在するすべてのファイルの一覧を取得する
string[] Files = System.IO.Directory.GetFiles(path, "*", System.IO.SearchOption.AllDirectories);
//ファイルをすべて削除する
Array.ForEach(Files, delegate(string FileName)
{
//ファイルの属性を取得する
System.IO.FileAttributes fa = System.IO.File.GetAttributes(FileName);
//リードオンリーがついている場合には
if ((fa & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
{
//リードオンリーをはずす
System.IO.File.SetAttributes(FileName, fa ^ System.IO.FileAttributes.ReadOnly);
}
//削除する
System.IO.File.Delete(FileName);
});
//ディレクトリを削除する
System.IO.Directory.Delete(path, true);
}
}
}