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

后端 未结 2 690
盖世英雄少女心
盖世英雄少女心 2020-11-27 11:13

I have a TextBox named textbox1 and a Button named button1. When I click on button1 I want to browse my file

相关标签:
2条回答
  • 2020-11-27 11:23
    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;
    
    0 讨论(0)
  • 2020-11-27 11:39

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题