196

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"
bluish
  • 23,093
  • 23
  • 110
  • 171
NoobMaster69
  • 2,201
  • 3
  • 16
  • 24

2 Answers2

452

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;
    }
}
Community
  • 1
  • 1
Klaus78
  • 10,948
  • 5
  • 28
  • 28
  • 23
    if (result.HasValue && result.Value) instead of if (result == true) – eflles Apr 26 '14 at 10:33
  • 2
    @efles what is the value your way provides over the official sample code at http://msdn.microsoft.com/en-us/library/microsoft.win32.openfiledialog.aspx ? – Dirk Bester Apr 30 '14 at 18:09
  • 7
    @eflles The sample is technically correct. From http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx: *When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal).* However I suppose it could be argued whether this is an exploitation of this technicality (I personally think it's OK in this case). – Ohad Schneider Jul 01 '14 at 22:00
24
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;
Dave
  • 787
  • 6
  • 9