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>
相关推荐
曹牧几秒前
JDK重定向目录
java·开发语言
郑州光合科技余经理3 分钟前
同城小程序开发:同一笔单在用户端和商家端各显示到哪
android·java·开发语言·前端·后端·uni-app·php
samble17 分钟前
从零搭建半导体设备上位机(二):Prism + DryIoc,五个工程与区域导航怎么串起来
wpf·prism·dryioc
2601_9628857233 分钟前
如何用 Python 计算溃疡指数(Ulcer Index)?
开发语言·python
kiracrimson44 分钟前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
一条闲鱼_mytube1 小时前
分布式 ID 生成方案:雪花算法与号段模式
分布式·算法·wpf
程序边界1 小时前
顶刊级论文配图全流程:用 Python 复刻 Nature/Science 风格图表
开发语言·python
普通人61 小时前
uniapp模版JS
开发语言·javascript·小程序·uni-app·1024程序员节
Msir_Modern1 小时前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
G018_star sky♬1 小时前
nodeJS他是如何用JavaScript封装C++的呢
开发语言·javascript·c++