Open file dialog and select a file using WPF controls and C#

C#WpfTextboxOpenfiledialog

C# Problem Overview


I have a TextBox named textbox1 and a Button named button1. When I click on button1 I want to browse my files to search only for image files (type jpg, png, bmp...). And when I select an image file and click Ok in the file dialog I want the file directory to be written in the textbox1.text like this:

textbox1.Text = "C:\myfolder\myimage.jpg"

C# Solutions


Solution 1 - C#

Something like that should be what you need

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 


    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();


    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;
    }
}

Solution 2 - C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoobMaster69View Question on Stackoverflow
Solution 1 - C#Klaus78View Answer on Stackoverflow
Solution 2 - C#DaveView Answer on Stackoverflow