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

问题描述 投票:0回答:3

我有一个名为

TextBox
textbox1
和一个名为
Button
button1
。 当我单击
button1
时,我想浏览我的文件以仅搜索图像文件(类型 jpg、png、bmp...)。 当我选择一个图像文件并在文件对话框中单击“确定”时,我希望将文件目录写入
textbox1.text
中,如下所示:

textbox1.Text = "C:\myfolder\myimage.jpg"
c# wpf textbox openfiledialog
3个回答
474
投票

类似的东西应该就是你所需要的

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

25
投票
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
投票

使用 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
}

参考:如何打开常用对话框|微软.Net 8

© www.soinside.com 2019 - 2024. All rights reserved.