68.浏览文件并选择文件 C#例子 WPF例子

OpenFileDialog是一个常用的对话框,允许用户浏览文件系统并选择文件。OpenFileDialog.ShowDialog()方法用于显示这个对话框,并且它会以模态方式运行,这意味着用户必须关闭对话框才能继续与应用程序的其他部分交互。

该代码会打开代码所在路径,你可以在里面创建文件夹,和文件,然后选中。文本框中就会填入选中文件的相对路径。

代码展示:

cs 复制代码
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;

namespace 路径填入
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "All files (*.*)|*.*"; // 可以根据需要设置文件过滤
            openFileDialog.InitialDirectory = baseDirectory; // 设置初始目录

            if (openFileDialog.ShowDialog() == true)
            {
                // 将选择的文件路径填入文本框
                string relativePath = System.IO.Path.GetRelativePath(baseDirectory, openFileDialog.FileName);

                FilePathTextBox.Text = relativePath;
            }
        }
    }
}
XML 复制代码
<Window x:Class="路径填入.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:路径填入"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox x:Name="FilePathTextBox" Width="300" Height="30" Margin="10"/>
        <Button Content="浏览" Click="BrowseButton_Click" Width="80" Height="30" Margin="350,0,0,0"/>
    </Grid>
</Window>
相关推荐
NPE~13 分钟前
[渗透测试]热门搜索引擎推荐— — fofa篇
开发语言·搜索引擎·渗透测试·php·教程·软件推荐·fofa
霍熠烁17 分钟前
Objective-C语言的云计算
开发语言·后端·golang
WANGWUSAN6636 分钟前
Python教程:使用Matplotlib模块画柱状图、饼形图、直方图
开发语言·经验分享·python·程序人生·matplotlib·数据可视化
饮长安千年月1 小时前
CVE-2024-13025-Codezips 大学管理系统 faculty.php sql 注入分析及拓展
开发语言·数据库·sql·网络安全·php
计算机视觉-Archer1 小时前
[NKU]C++安装环境 VScode
开发语言·c++
东方忘忧1 小时前
QT全局所有QSS样式实时切换
开发语言·数据库·qt
csdn_aspnet2 小时前
ASP.NET Core 如何使用 C# 从端点发出 GET 请求
c#·asp.net·.netcore
关关钧2 小时前
【R语言】相关系数
开发语言·python·r语言
六毛的毛2 小时前
后端开发ThreadLocal简介
java·开发语言
朴拙数科3 小时前
如何使用 Python 高效操作 Word 文档:python-docx 和 comtypes 介绍与实践
python·c#·word