1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

フォルダを削除するコード。

Posted at

フォルダが空になったときに、フォルダを削除したいことはよくある。
でも、一見フォルダが空でも、じつはフォルダを削除できないことはある。
隠蔽ファイルがあるためだ。
そこで、キャッシュ系の隠蔽ファイルを削除して、ファイルが0ならフォルダを削除するコード。

List<string> folders = new List<string>(Directory.GetDirectories(dataroot, "*", SearchOption.AllDirectories));
folders.Reverse();
string[] notneedfiles = new string[] {"DS_Store", //MacOSXのフォルダ情報ファイル
"Desktop.ini", //Windowsのフォルダ情報ファイル
"Thumbs.db", //Windowsのサムネイルのキャッシュ
"folder$", //WindowsXPの偽フォルダファイル
"_CATALOG.VIX", //VIXのサムネイルのキャッシュ
"_THUMBS_.DVI", //Linarのサムネイルのキャッシュ
"_THUMBNL.SUE", //Susieのサムネイルのキャッシュ
"PREVIEW.PIX", //Painterのサムネイルのキャッシュ
"^folder.jpg$",
"albumart*.jpg",
"ini$"};
string notneeds = "(" + string.Join("|", notneedfiles).ToLower() + ")";
foreach (string folder in folders) {
	List<string> files = new List<string>( Directory.GetFiles(folder, "*"));
	foreach (string file in files)
		//隠しファイルを削除する。
		if (Regex.Match(Path.GetFileName(file).ToLower(), notneeds).Success)
			File.Delete(file);
	files = new List<string>(Directory.GetFiles(folder, "*"));
	files.AddRange(Directory.GetDirectories(folder, "*"));
	if (files.Count == 0)
		Directory.Delete(folder);
}
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?