C#でサブディレクトリ配下の全てのファイルを取得する
DOSコマンドなら「dir /s /b」で一瞬なんだけどな~~
で、C#で同じことしようとすると、メソッドの再帰処理1)が必要になってきます。
参考文献:https://dianxnao.com/%E3%82%B5%E3%83%96%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%82%82%E5%90%AB%E3%82%81%E3%81%9F%E5%85%A8%E3%81%A6%E3%81%AE%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D%E5%8F%96%E5%BE%97/
C#でC:\配下を検索しようとすると、どうしてもゴミ箱とかアプリケーションによるアクセスが禁止されている箇所を検索したタイミングで例外が発生するらしい。
以下の例はtouchコマンドを作ってみるよで作成(とうよりほぼ参考文献まま)したサブディレクトリ配下の検索をするためのメソッドです。検索した物がディレクトリなのかファイルなのか区別する必要があったのでDorFクラスを作成しています。
internal class DorF
{
public string PathName;
public pathKinder PathKind;
public DorF(string pathName , pathKinder pathKind)
{
PathName = pathName;
PathKind = pathKind;
}
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <exception cref="Exception"></exception>
public void setLastWriter(DateTime dt)
{
try
{
if (PathKind == pathKinder.file)
{
File.SetLastWriteTime(PathName, dt);
}
else
{
Directory.SetLastWriteTime(PathName, dt);
}
}catch (Exception ex)
{
throw new Exception(ex.Message, ex.InnerException);
}
}
}
protected static List<DorF> getAllFiles(string path,string filePtn, SearchOption sh,bool isDir)
{
List<DorF> lstStr = new List<DorF>();
try
{
var files = Directory.EnumerateFiles(path,filePtn);
foreach (var file in files)
{
lstStr.Add(new DorF(file, pathKinder.file));
}
var dirs = Directory.EnumerateDirectories(path);
foreach (var dir in dirs)
{
if (isDir)
{
lstStr.Add(new DorF(dir, pathKinder.directory));
}
if (sh.Equals(SearchOption.AllDirectories))
{
lstStr.AddRange(getAllFiles(dir,filePtn,sh,isDir));
}
}
}catch (UnauthorizedAccessException e)
{
Console.WriteLine(LocalizeReader.GetResourceValue("msg0002", false));
}catch (Exception e)
{
throw new UserFileException(e.Message, e.InnerException);
}
return lstStr;
}
1)
メソッドの中でメソッドを呼び出す