我有一个名为
TextBox
的 textbox1
和一个名为 Button
的 button1
。
当我单击 button1
时,我想浏览我的文件以仅搜索图像文件(类型 jpg、png、bmp...)。
当我选择一个图像文件并在文件对话框中单击“确定”时,我希望将文件目录写入 textbox1.text
中,如下所示:
textbox1.Text = "C:\myfolder\myimage.jpg"
类似的东西应该就是你所需要的
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;
使用 OpenFileDialog 类。
using Microsoft.Win32;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
fileDialog.Title = "Select image file(s)...";
fileDialog.Multiselect = true; // Set to false or never mention this line for single file select
var success = fileDialog.ShowDialog();
if (success == true)
{
var paths = fileDialog.FileNames; // Use fileDialog.FileName for a single file - no 's' at the end
var fileNames = fileDialog.SafeFileNames; // Use fileDialog.SafeFileName for a single file - no 's' at the end
}