ファイルを開くダイアログを使用する - WPF

WPFアプリケーションで[ファイルを開く]コモンダイアログを表示したいことがあります。WPFアプリケーションではダイアログはコンポーネントとして用意されていないため、OpenFileDialogクラスのインスタンスを作成してダイアログを表示します。

コード例 (MainWindows.xaml.cs)

以下の例では、button1をクリックすると[ファイルを開く]ダイアログを表示します。ファイルを選択しダイアログの開くボタンを押すと選択したファイル名をtextBox_FileNameに表示します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Microsoft.Win32; //追加

namespace CSVParser
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
      OpenFileDialog ofd = new OpenFileDialog();
      ofd.FileName = "";
      ofd.DefaultExt = "*.*";
      if (ofd.ShowDialog() == true) {
        textBox_FileName.Text = ofd.FileName;
      }
    }
  }
}

プログラム例

WPFアプリケーションを作成します。

UI

下図のUIを作成します。フォームにボタンとテキストボックスを配置します。

コード

下記のコードを記述します。
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;

namespace WpfOpenFileDialog
{
  /// <summary>
  /// MainWindow.xaml の相互作用ロジック
  /// </summary>
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      OpenFileDialog dialog = new OpenFileDialog();
      dialog.FileName = "";
      dialog.DefaultExt = "*.*";
      if (dialog.ShowDialog() == true) {
        textBox_FileName.Text = dialog.FileName;
      }
    }
  }
}

解説

下記のコードでOpenFileDialogのオブジェクトの作成とプロパティの設定をします。
  OpenFileDialog dialog = new OpenFileDialog();
  dialog.FileName = "";
  dialog.DefaultExt = "*.*";

ShowDialogメソッドを呼び出しダイアログを表示します。ダイアログでファイルが選択された場合は、ShowDialogの戻り値が true になります。ファイル選択された場合はダイアログボックスで選択されたファイル名のフルパスをテキストボックスに表示します。
  if (dialog.ShowDialog() == true) {
    textBox_FileName.Text = dialog.FileName;
  }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。[Button]をクリックします。


[Button]をクリックするとファイルを開くダイアログが表示されます。


ダイアログでファイルを選択します。今回は C:\data フォルダにある "sample.wav" ファイルを選択します。ダイアログボックスの[開く]ボタンをクリックします。


ダイアログボックスでファイルが選択されたため、テキストボックスにダイアログで選択されたファイルのフルパスが表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2010-08-13
iPentec all rights reserverd.