この資料では、コード例を使用して、ルート ディレクトリから順にサブディレクトリを再帰的に調べてファイルを検索する方法について手順を追って説明します。検索文字列を指定して、特定の条件に一致するファイルを検索できるようにします。必要に応じて、コードの各部分について説明しています。資料の最後に、実際に動作するコード サンプルも示します。
ディレクトリの再帰呼び出しは、開発者にとって一般的な入出力作業です。コンポーネント オブジェクト モデル (COM) アプリケーションでは、FileSystemObject を使用して、この処理を簡単に実行できます。.NET では、これがさらに簡単になりました。FileSystemObject の場合と同様、System.IO 名前空間内のクラスに、ファイルやディレクトリに対するオブジェクト指向のアクセス方法が用意されています。
先頭へ戻る
必要条件
• |
Microsoft Visual C# 2005 または Microsoft Visual C# .NET
|
先頭へ戻る
ディレクトリの再帰呼び出し
ファイルおよびディレクトリを操作するクラスは、System.IO 名前空間にあります。これらのクラスを使用する前に、以下の名前空間をプロジェクトにインポートする必要があります。
using System.IO;
System.IO 名前空間のクラスは、ファイルおよびディレクトリ関連の処理に多くの選択肢を提供します。この名前空間では、インスタンスを作成できるクラスのほか、ファイルおよびディレクトリのユーティリティ クラスも用意されています。これらのクラスには、その型の変数を宣言しなくても呼び出せる静的メソッドが含まれています。たとえば、Directory オブジェクトを使用して所定のディレクトリのサブディレクトリを取得できます。
以下のコードでは、Directory オブジェクトの静的メソッド GetDirectories を使用して文字列の配列を取得します。この配列には、C:\ ディレクトリのサブディレクトリ (存在する場合) へのディレクトリ パス名が含まれています。
string[] directories = Directory.GetDirectories("C:\\");
また、Directory オブジェクトには、GetFiles と呼ばれるメソッドもあります。このメソッドを使用して、特定の条件に一致するファイルの文字列型配列を取得できます。次のコード サンプルでは、File オブジェクトを使用して、C:\ ディレクトリにある .dll 拡張子で終わるすべてのファイルを取得します。
string[] files = Directory.GetFiles("C:\\", "*.dll");
Directory オブジェクトの GetDirectories メソッドと GetFiles メソッドを使用すると、検索文字列に一致するファイルを再帰的に検索することができます。再帰呼び出しを実行するには、以下の方法を使用します。
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
上記のコードでは、検索するディレクトリが含まれている文字列を DirSearch に渡します。この文字列値は、ディレクトリの完全なパス名です。GetDirectories を使用すると、プロシージャに渡されるディレクトリのサブディレクトリを取得できます。GetDirectories は配列を返すため、for/each ステートメントを使用して、各サブディレクトリについて反復処理を行うことができます。各サブディレクトリでは、GetFiles メソッドを使用してディレクトリ内のファイルについて反復処理を行います。GetFiles には、フォーム上のテキスト ボックスの値が渡されます。このテキスト ボックスには、GetFiles から返される結果をフィルタ処理する検索文字列が含まれています。検索条件に一致するファイルがあれば、リスト ボックスに追加されます。配置されているサブディレクトリごとに DirSearch を再度呼び出し、サブディレクトリを渡します。このような再帰呼び出しを使用することによって、所定のルート ディレクトリのすべてのサブディレクトリを検索できます。
先頭へ戻る
完全なコード リスト
1. |
Visual C# の新しい Windows アプリケーション プロジェクトを開始します。デフォルトで Form1 が作成されます。
|
2. |
[表示] メニューの [ソリューション エクスプローラ] をクリックして表示します。
|
3. |
ソリューション エクスプローラで [Form1.cs] を右クリックし、[コードの表示] をクリックします。
|
4. |
Form1 のコード ウィンドウで、表示されているコードをすべて強調表示し、削除します。
|
5. |
Form1 のコード ウィンドウに以下のコードを貼り付けます。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace RecursiveSearchCS
{
/// <summary>
/// Summary description for Form1
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
internal System.Windows.Forms.Button btnSearch;
internal System.Windows.Forms.TextBox txtFile;
internal System.Windows.Forms.Label lblFile;
internal System.Windows.Forms.Label lblDirectory;
internal System.Windows.Forms.ListBox lstFilesFound;
internal System.Windows.Forms.ComboBox cboDirectory;
/// <summary>
/// Required designer variable
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call.
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support: do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnSearch = new System.Windows.Forms.Button();
this.txtFile = new System.Windows.Forms.TextBox();
this.lblFile = new System.Windows.Forms.Label();
this.lblDirectory = new System.Windows.Forms.Label();
this.lstFilesFound = new System.Windows.Forms.ListBox();
this.cboDirectory = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// btnSearch
//
this.btnSearch.Location = new System.Drawing.Point(608, 248);
this.btnSearch.Name = "btnSearch";
this.btnSearch.TabIndex = 0;
this.btnSearch.Text = "Search";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// txtFile
//
this.txtFile.Location = new System.Drawing.Point(8, 40);
this.txtFile.Name = "txtFile";
this.txtFile.Size = new System.Drawing.Size(120, 20);
this.txtFile.TabIndex = 4;
this.txtFile.Text = "*.dll";
//
// lblFile
//
this.lblFile.Location = new System.Drawing.Point(8, 16);
this.lblFile.Name = "lblFile";
this.lblFile.Size = new System.Drawing.Size(144, 16);
this.lblFile.TabIndex = 5;
this.lblFile.Text = "Search for files containing:";
//
// lblDirectory
//
this.lblDirectory.Location = new System.Drawing.Point(8, 96);
this.lblDirectory.Name = "lblDirectory";
this.lblDirectory.Size = new System.Drawing.Size(120, 23);
this.lblDirectory.TabIndex = 3;
this.lblDirectory.Text = "Look In:";
//
// lstFilesFound
//
this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
this.lstFilesFound.Name = "lstFilesFound";
this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
this.lstFilesFound.TabIndex = 1;
//
// cboDirectory
//
this.cboDirectory.DropDownWidth = 112;
this.cboDirectory.Location = new System.Drawing.Point(8, 128);
this.cboDirectory.Name = "cboDirectory";
this.cboDirectory.Size = new System.Drawing.Size(120, 21);
this.cboDirectory.TabIndex = 2;
this.cboDirectory.Text = "ComboBox1";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(688, 277);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnSearch,
this.txtFile,
this.lblFile,
this.lblDirectory,
this.lstFilesFound,
this.cboDirectory});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
lstFilesFound.Items.Clear();
txtFile.Enabled = false;
cboDirectory.Enabled = false;
btnSearch.Text = "Searching...";
this.Cursor = Cursors.WaitCursor;
Application.DoEvents();
DirSearch(cboDirectory.Text);
btnSearch.Text = "Search";
this.Cursor = Cursors.Default;
txtFile.Enabled = true;
cboDirectory.Enabled = true;
}
private void Form1_Load(object sender, System.EventArgs e)
{
cboDirectory.Items.Clear();
foreach (string s in Directory.GetLogicalDrives())
{
cboDirectory.Items.Add(s);
}
cboDirectory.Text = "C:\\";
}
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
} 注 : Visual Studio 2005 では、コードを変更する必要があります。Visual C# では、Windows フォーム プロジェクトを作成すると、デフォルトで Form1 という名前のフォームがプロジェクトに追加されます。このフォームを表す 2 つのファイルは、Form1.cs と Form1.designer.cs です。ユーザーによるコードの記述は Form1.cs で行います。Form1.designer.cs ファイルには、Windows フォーム デザイナによってコードが書き込まれます。
Visual C# 2005 の Windows フォーム デザイナの詳細については、次の MSDN (Microsoft Developer Network) Web サイトを参照してください。
|
6. |
F5 キーを押してサンプル プログラムをビルドし、実行します。
|
先頭へ戻る
関連情報については、次のマイクロソフトの Web サイトで Microsoft .NET Framework SDK クイックスタート チュートリアルを参照してください。
関連情報を参照するには、以下の「サポート技術情報」 (Microsoft Knowledge Base) をクリックしてください。
306777 (http://support.microsoft.com/kb/306777/)
[HOW TO] Visual C# .NET と System.IO を使ってテキスト ファイルを読み取る方法
Visual C# .NET の一般的な詳細については、次の Usenet のニュースグループを参照してください。
Visual C# .NET 内のディスカッション (http://www.microsoft.com/japan/msdn/newsgroups/default.mspx?dg=microsoft.public.jp.dotnet.languages.csharp&lang=ja&cr=JP&r=24b839f0-e80c-4305-a265-84d577c03c8a)
先頭へ戻る