フォルダにあるファイルの一覧を取得する
フォルダにあるファイルの一覧を取得する
DirectoryクラスのGetFilesメソッドを使用することで、指定したフォルダ内にあるファイルの一覧を取得することが出来ます。
System.IO.Directory.GetFiles(フォルダパス);
System.IO.Directory.GetFiles(フォルダパス, パターン);
System.IO.Directory.GetFiles(フォルダパス, パターン, true/false);
第一引数には一覧を取得したいフォルダのパスを指定します。第二引数には"*"や"?"などのワイルドカードと呼ばれる特殊文字を渡します。
このワイルドカードは"*"が任意の長さの文字、"?"が任意の一文字に相当します。
また、第三引数にtrueを指定することでフォルダ内にあるサブフォルダ内のファイルも同時に取得します。
引数に指定した文字列の長さが0だった場合ArgumentExceptionの例外が発生します。
また、引数がNullの場合ArgumentNullExceptionの例外が発生します。
引数にフォルダではなくファイルを指定した場合IOExceptionの例外が発生します。
private void button1_Click(object sender, EventArgs e) { if (true == System.IO.Directory.Exists("./Sample")) { if (false == System.IO.File.Exists("./Sample/a.txt")) { System.IO.File.CreateText("./Sample/a.txt"); } if (false == System.IO.File.Exists("./Sample/bc.txt")) { System.IO.File.CreateText("./Sample/bc.txt"); } foreach (string name in System.IO.Directory.GetFiles("./Sample")) { MessageBox.Show(name); } foreach (string name in System.IO.Directory.GetFiles("./Sample", "?.txt")) { MessageBox.Show("?.txt : " + name); } foreach (string name in System.IO.Directory.GetFiles("./Sample","*.txt")) { MessageBox.Show("*.txt : " + name); } } else if (false == System.IO.Directory.Exists("./Sample")) { MessageBox.Show("Sampleフォルダは存在しません。"); } }