LoginSignup
2
0

More than 1 year has passed since last update.

指定ディレクトリにあるファイル名をリストで取得する

Posted at

指定ディレクトリにあるExcelファイル名の一覧をリストで取得した。

指定ディレクトリにあるファイル名をリストで取得する

必要なusing記述

using System.IO;

String型の配列を作成し、そこにファイル名の一覧が入る。

string[] files = Directory.GetFiles(@"C:\Users", "*.xlsx", System.IO.SearchOption.TopDirectoryOnly);

第一引数:指定ディレクトリまでのパス
第二引数:取得したいファイルの種類
     Excelファイルを取得する場合 ".xlsx"
     すべての種類のファイルを取得したい場合 "*"
     ファイル名の文字数を指定したい場合 "?????.xlsx" 
第三引数:指定ディレクトリにあるファイルのみを取得する SearchOption.TopDirectoryOnly
     サブフォルダにあるファイルも取得する SearchOption.AllDirectories


あとは配列の要素を取得するコードを書けばOK。
    

応用編


パス情報をApp.configで指定する
と組み合わせて使用した。

App.configでディレクトリまでを指定しておく。

App.config
<appSettings>
<add key="FilePath" value="C:\Users" />  
</appSettings>

※パスの区切りのバックスラッシュ(\)は、実際のApp.configの見た目では¥になっています。(おそらく日本語環境を使用しているとそうなる)

組み合わせたコード↓

string[] files = Directory.GetFiles(ConfigurationManager.AppSettings["FilePath"], "*.xlsx", System.IO.SearchOption.TopDirectoryOnly);

参考:
C#でフォルダ内のファイル名一覧を取得する

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0