WPF中使用OpenFileDialog打开文件

添加Microsoft.Win32程序集

private void OnOpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Load a file";
            if(openFileDialog.ShowDialog() == true)
            {
         // 获得所选中文件的文件名(全称) txfilename.Text
= openFileDialog.FileName; using(StreamReader sr = new StreamReader(txfilename.Text)) {
            // 读入文件的全部内容
string text = sr.ReadToEnd(); } } }

OpenFileDialog的属性:

AddExtension 将扩展名自动添加到文件名上

CheckFileExists 用户指定不存在的文件时显示警告

CheckPathExists 从对话框返回前,检查指定路径是否存在

Filter 筛选出符合要求的文件,比如*.cs|*.txt等

InitialDirectory 指定对话框的初始目录

Multiselect 是否可以选择多个文件

RestoreDirectory 对话框在关闭前是否恢复当前目录

Title 指定打开的对话框的名字

原文地址:https://www.cnblogs.com/larissa-0464/p/13197512.html