[ VB.NET / C# ] ファイル名をパターンマッチ検索 ( Directory.GetFileSystemEntries )

Pocket

特定のフォルダ内に存在するファイルをファイル名でパターン検索して、条件に一致する ファイルパスのリストを取得するサンプルコードです。Directory.GetFileSystemEntries メソッドを使用しています。

スポンサーリンク

.NetFramework4 以降では、Directory.GetFileSystemEntries メソッドの第3パラメータでサブディレクトリを含むか否かを 指定することができますが、それ以前のバージョンではサブディレクトリを含んだ検索はできません。

検索するディレクトリにあるファイル

仮に検索ディレクトリ内に以下のファイルが存在しているものとします。

  1. A_2011年2月.xml
  2. B_2011年2月.xml
  3. A_2011年月.xml

サンプルコード

VB.NET

'Imports System.IO

Dim dirPath As String = "D:\search" ' 検索するディレクトリ

' 対象ファイルを検索する
Dim fileList As String() = Directory.GetFileSystemEntries(dirPath, "A_*年*月.xml")

' 抽出したファイル数を出力
Console.WriteLine("file num = " + fileList.Length.ToString())
For Each filePath As String In fileList
    ' ファイルパスを出力
    Console.WriteLine("file path = " + filePath)
Next

C#

using System.IO;

string dirPath = @"D:\search"; // 検索するディレクトリ

// 対象ファイルを検索する
string[] fileList = Directory.GetFileSystemEntries(dirPath, @"A_*年*月.xml");

// 抽出したファイル数を出力
Console.WriteLine("file num = " + fileList.Length.ToString());
foreach(string filePath in fileList) {
    // ファイルパスを出力
    Console.WriteLine("file path = " + filePath);
}

実行結果

file num = 2
file path = D:\search\A_2011年2月.xml
file path = D:\search\A_2011年月.xml

「*」は 0個以上何かしら文字が入っているという意味なので、入力されていない場合でも問題なく抽出されます。仮にパターン文字列を「A_*年?月.xml」のように、1文字をあらわす「?」に変更すると、抽出される結果は 以下のようになります。

実行結果(その2)

file num = 1
file path = D:\search\A_2011年2月.xml

参考

 

スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *