【Winforms】特定フォルダ内のテキストファイルをすべて取得する
C#で特定フォルダ内のテキストファイルを取得するための簡単なサンプルコードを以下に示します。このコードは、System.IO
名前空間を使用して、指定されたディレクトリ内の.txt
拡張子を持つすべてのファイルを取得します。取得したファイルパスはコンソールに出力されます。
サンプル
デザイン
2つのTextBoxを配置します

用意するファイル
実行ファイルと同じフォルダに2つのテキストファイル(.txt)を用意します
TextFile1.txt
内容)テキストファイル1の内容
TextFile2.txt
内容)テキストファイル2の内容
TextFile3.txt
内容)テキストファイル3の内容

コード
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// テキストファイルを検索するディレクトリのパス
// (今回は、ワーキングディレクトリ)
string folderPath = @".\";
// 指定されたディレクトリ内のすべてのテキストファイルを取得
string[] files = Directory.GetFiles(folderPath, "*.txt");
// 各ファイルの内容を読み込み、出力
foreach (string file in files)
{
// ファイルの内容を読み込む
string content = File.ReadAllText(file);
// ファイル名とその内容をTextBoxに出力
textBox1.Text += $"File: {file}\r\n";
textBox2.Text += content + "\r\n";
}
}
}
実行結果

参考
サブフォルダも含め全てのテキストファイルを取得するには
直下のファイルのみ
string[] files = Directory.GetFiles(folderPath, "*.txt");
サブフォルダを含める
string[] files = Directory.GetFiles(folderPath, "*.txt", SearchOption.AllDirectories);
実行結果
最後の行になりますが、Sampleフォルダ内にSample.txtファイルを追加しています
ファイルの内容は「ZZZZZ」になります

ディスカッション
コメント一覧
まだ、コメントがありません