WPF OpenFileDialog

This article will tell you how to use OpenFileDialog using WPF. OpenFileDialog represents a common dialog box that displays the control that allows the user to open a file. This class cannot be inherited.

First of all make a new WPF application and go to .xaml window.

        <Button Content="Browse" Height="32" HorizontalAlignment="Left"
                Margin="20,12,0,0" Click="button1_Click"
                Name="button1" VerticalAlignment="Top" Width
="136" />
        <Image Margin="12,70,0,20" Name="MyImage" Stretch="Fill" HorizontalAlignment="Left" Width="200" />
        <ListBox Margin="263,70,46,20" Name="listBox1" />


private void button1_Click(object sender, RoutedEventArgs e)
            Stream checkStream = null;
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

            openFileDialog.Multiselect = false;
openFileDialog.InitialDirectory = "c:\\";
            //if you want filter only .txt file
            //dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

            //if you want filter all files           
            openFileDialog.Filter = "All Image Files | *.*";

            if ((bool)openFileDialog.ShowDialog())
                    if ((checkStream = openFileDialog.OpenFile()) != null)
                       MyImage.Source = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute));
                        MessageBox.Show("Successfully done");
                 catch (Exception ex)
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);


                MessageBox.Show("Problem occured, try again later");


Now run application. You will see result like this.


Figure 1.

When you click on Browse button that wil open your given directory name, if you does't give InitialDirectory name then that will open Pictures directory.