How to use OpenFileDialog control in wpf to read txt file

July 04, 2015 0 Comments

Today i am talking about OpenFileDialog control. This control is used for picking some files from computer drive or location. I have already learn about OpenFileDialog control in windows form article. Today, the same article i cover using WPF. The logics are same in all language but some presentation of the language are different Like previous article cover by windows form and this article present by xaml language. Lets take a simple example: In this example, we will pick the text file from computer and read this file by using TextBox.

        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="44" Margin="39,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/>
        <Button x:Name="button" Content="Browse" HorizontalAlignment="Left" Margin="344,33,0,0" VerticalAlignment="Top" Width="130" Height="44" Click="button_Click"/>
        <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="152" Margin="59,108,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="386"/>


Code behind file

  private void button_Click(object sender, RoutedEventArgs e)
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = ".txt";
            ofd.Filter = "Text Document (.txt)|*.txt";
                string filename = ofd.FileName;
                textBox.Text = filename;
                textBox1.Text = File.ReadAllText(filename);

Here OpenFileDialog control is exist in Microsoft.Win32 namespace. So use it by using "using" keyword. If you want to take only text file by this control then use Filter property. After picked file you can read this by using ReadAllText method of  File class.

Now , code generate the following output
How to use OpenFileDialog control in wpf to read txt file

Jacob Lefore

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google