[.NET クラスライブラリ Tips][Directory] 指定したディレクトリ内のファイルやディレクトリをすべて列挙する

スポンサーリンク

本記事の概要

この記事では、Directory クラスを使用して、指定したディレクトリ内のファイルやディレクトリをすべて列挙する方法について説明します。

公式サイト情報はコチラを参照してください。

 

指定したディレクトリ内のファイルやディレクトリをすべて列挙するするには?

指定したディレクトリ内のファイルやディレクトリをすべて列挙するには GetFileSystemEntries メソッドを使用します。

構文は以下に示す通り複数あります。

public static string[] GetFileSystemEntries (string path);
public static string[] GetFileSystemEntries (string path, 
    string searchPattern);
public static string[] GetFileSystemEntries (string path, 
    string searchPattern, 
    System.IO.EnumerationOptions enumerationOptions);
public static string[] GetFileSystemEntries (string path, 
    string searchPattern, System.IO.SearchOption searchOption);

指定したパス内のすべてのファイル名とサブディレクトリ名を取得する

以下の構文を使用することで、指定したディレクトリのファイルを取得することができます。

public static string[] GetFileSystemEntries (string path);

以下の例では、C:¥Work 直下にあるファイルとフォルダを取得して表示します。

using System.IO;

var targetPath = @"C:\Work";

foreach(var filename in Directory.GetFileSystemEntries(targetPath))
{
    Console.WriteLine(filename);
}

実行例を以下に示します。

実行例

実行例

 

指定したパス内の検索パターンに一致するファイル名とディレクトリ名を取得する

以下の構文を使用すると、指定したパス内の検索パターンに一致するファイル名とディレクトリ名を取得することができます。

public static string[] GetFileSystemEntries (string path, 
    string searchPattern);

以下の例では、C:¥Work 配下にある、”01″ が含まれるファイル名やディレクトリ名を取得して表示します。

using System.IO;

var targetPath = @"C:\Work";

foreach(var filename in Directory.GetFileSystemEntries(targetPath,"*01*"))
{
    Console.WriteLine(filename);
}

 

.NET クラスライブラリ Tips

これまでに紹介した .NET クラスライブラリ Tips はコチラから参照できます。

Please follow and like us:

コメント

タイトルとURLをコピーしました