Friday, February 25, 2011

How to use OpenFileDialog in WPF

The OpenFileDialog is used to browse files on a machine. 

The OpenFileDialog class defined in Microsoft.Win32.OpenFileDialog namespace represents an OpenFileDialog control in WPF. 

Let's add a TextBox and a Button control to a XAML page. The window looks like this.

When you click the Browse button, we will browse text files and set the TextBox.Text to the selected file name.
<TextBox Height="25" HorizontalAlignment="Left" Margin="41,104,0,0" Name="txtFileUpload" VerticalAlignment="Top" Width="405" Grid.RowSpan="2" />

<Button Content="Browse" Height="26" HorizontalAlignment="Left" Margin="448,103,0,0" Name="btnBrowse" VerticalAlignment="Top" Width="75" Click="btnBrowse_Click" />
The code listed in Listing 1 creates an OpenFileDialog, set its default extension and filter properties and calls ShowDialog method that displays the dialog. Once the OpenFileDialog is displayed, you can use it to browse files. Once file is selected, the FileName property of the OpenFileDialog is set to the selected file name. This code sets the selected file name as a TextBox.Text property.
private void btnBrowse_Click(object sender, RoutedEventArgs e)
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "File Upload";
            fdlg.Filter = "Xml File|*.xml";
            //fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            Nullable<bool> result = fdlg.ShowDialog();
            if (result==true)
                txtFileUpload.Text = fdlg.FileName;


  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it.., c#, javascript
    Thanks a lot..!

  2. Really Nice Information,Thank You Very Much For Sharing.
    Web Development Company