Japan*
クイック ナビ|ホーム|各国のサイト
Microsoft*
Microsoft.comJapanサイトの検索:
サポート オンライン 
|技術情報の検索|製品別 サポート ページ|製品別 お問い合わせ

Visual C# を使用してディレクトリを再帰的に検索する方法

文書番号:303974
最終更新日:2006年10月4日
リビジョン:3.1
この記事は、以前は次の ID で公開されていました: JP303974
Microsoft Visual C++ .NET については、次の資料を参照してください。307009 (http://support.microsoft.com/kb/307009/)
Microsoft Visual Basic .NET については、次の資料を参照してください。306666 (http://support.microsoft.com/kb/306666/)

この資料では、次の Microsoft .NET Framework クラス ライブラリの名前空間を参照しています。
System.IO
目次

概要

この資料では、コード例を使用して、ルート ディレクトリから順にサブディレクトリを再帰的に調べてファイルを検索する方法について手順を追って説明します。検索文字列を指定して、特定の条件に一致するファイルを検索できるようにします。必要に応じて、コードの各部分について説明しています。資料の最後に、実際に動作するコード サンプルも示します。

ディレクトリの再帰呼び出しは、開発者にとって一般的な入出力作業です。コンポーネント オブジェクト モデル (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 サイトを参照してください。
http://msdn2.microsoft.com/ja-jp/library/ms173077.aspx (http://msdn2.microsoft.com/ja-jp/library/ms173077.aspx)
6. F5 キーを押してサンプル プログラムをビルドし、実行します。

先頭へ戻る

関連情報

関連情報については、次のマイクロソフトの Web サイトで Microsoft .NET Framework SDK クイックスタート チュートリアルを参照してください。
http://ja.gotdotnet.com/quickstart/default.aspx (http://ja.gotdotnet.com/quickstart/default.aspx)
関連情報を参照するには、以下の「サポート技術情報」 (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)

先頭へ戻る


この資料は以下の製品について記述したものです。
Microsoft Visual C# 2005
Microsoft Visual C# .NET 2002 Standard Edition

先頭へ戻る

キーワード: 
kbhowtomaster kbio KB303974

先頭へ戻る

"Microsoft Knowledge Baseに含まれている情報は、いかなる保証もない現状ベースで提供されるものです。Microsoft Corporation及びその関連会社は、市場性および特定の目的への適合性を含めて、明示的にも黙示的にも、一切の保証をいたしません。さらに、Microsoft Corporation及びその関連会社は、本文書に含まれている情報の使用及び使用結果につき、正確性、真実性等、いかなる表明・保証も行ないません。Microsoft Corporation、その関連会社及びこれらの権限ある代理人による口頭または書面による一切の情報提供またはアドバイスは、保証を意味するものではなく、かつ上記免責条項の範囲を狭めるものではありません。Microsoft Corporation、その関連会社 及びこれらの者の供給者は、直接的、間接的、偶発的、結果的損害、逸失利益、懲罰的損害、または特別損害を含む全ての損害に対して、状況のいかんを問わず一切責任を負いません。(Microsoft Corporation、その関連会社 またはこれらの者の供給者がかかる損害の発生可能性を了知している場合を含みます。) 結果的損害または偶発的損害に対する責任の免除または制限を認めていない地域においては、上記制限が適用されない場合があります。なお、本文書においては、文書の体裁上の都合により製品名の表記において商標登録表示、その他の商標表示を省略している場合がありますので、予めご了解ください。"

サポート技術情報の検索

 
高度な検索を使う

サポート技術情報の翻訳

 

製品別 サポート ページ

その他のサポート オプション

  • 製品別 お問い合わせ
    電話や電子メールでマイクロソフトへ問い合わせる。
  • カスタマー インフォメーション センター
    製品の購入やプライバシーなどに関する情報など、技術情報以外のお問い合わせ窓口です。
  • マイクロソフト コミュニティ
    マイクロソフト製品や関連技術に関する知識とニュースを共有することを目的に、ユーザーの皆様、各分野のエキスパートなどの間で情報交換する場です。
  • KB ご利用の際のご注意
    お使いの Windows 環境によっては、"\" (バックスラッシュ) は "¥" (円記号) と表示される場合があります。

ページ ツール


©2007MicrosoftCorporation.Allrightsreserved. 使用条件 |商標 |プライバシー |日本での個人情報の取り扱い