ディレクトリ内のファイルのリストを返すには、次のメソッドがあります。
public IEnumerable<FileInfo> GetFilesRecursiveEnumerable(DirectoryInfo dir)
{
if (dir == null) throw new ArgumentNullException();
IList<FileSystemInfo> files = new List<FileSystemInfo>();
try
{
files = dir.GetFileSystemInfos();
}
catch (UnauthorizedAccessException) { } //ignore
catch (PathTooLongException)
{
MessageBox.Show("Path too long in directory: " + dir.FullName);
}
foreach (FileSystemInfo x in files)
{
DirectoryInfo dirInfo = x as DirectoryInfo;
if (dirInfo != null)
{
foreach (FileInfo f in GetFilesRecursiveEnumerable(dirInfo))
{
yield return f;
}
}
else
{
FileInfo fInfo = x as FileInfo;
if (fInfo != null) yield return fInfo;
}
}
}
このメソッドはGUIをブロックします。これをバックグラウンドスレッド(シングルのみ)で実行して、FileSystemInfo
オブジェクトが使用可能になったときに呼び出し元に渡されるようにします。
このメソッドをBackgroundワーカーで実行し、sを返すことができましたICollection
がFileSystemInfo
、リスト全体が返されますが、見つかったアイテムを生成したいと思います。
編集
達成しようとしていることを再評価する必要があるようです(おそらく、これはIEnumerableではなくコールバックを必要とします)
基本的に、ドライブに相当するファイルのインデックスを作成したいのですが、これをバックグラウンドスレッドで実行したいと思います。そうすれば、ファイルごとに(おそらく、Dirごとに)処理でき、必要に応じて、後の段階でプロセスを再開できます。非常に効果的に、呼び出し元(GUIスレッド)にこのメソッドを実行してもらいたいのですが、ディレクトリスキャン中に通知され、完全に終了したときではありません。たとえば、
//My original thoughts, but maybe need to tackle this a different way
public void ScanDrive()
{
foreach(FileInfo f in GetFilesRecursiveEnumerable())
{
//index file
//record the directory I am up to so I can resume later
/Keeping my application responsive to perform other tasks
}
}