打开文件对话框并使用WPF控件和C#选择文件

我有一个名为textbox1TextBox和一个名为button1Button。 当我点击button1时,我想浏览我的文件,只搜索图像文件(类型JPG,PNG,BMP..)。 当我选择一个图像文件并在文件对话框中单击“确定”时,我希望文件目录以textbox1.text写入,如下所示:

textbox1.Text = "C:\myfolder\myimage.jpg"
276331 次浏览

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;
}
}
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;