wpf 选择文件夹

两种方法

1

添加System.Windows.Forms的引用

System.Windows.Forms.FolderBrowserDialog openFileDialog = new System.Windows.Forms.FolderBrowserDialog(); //选择文件夹
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)//注意,此处一定要手动引入System.Window.Forms空间,否则你如果使用默认的DialogResult会发现没有OK属性
{
txb_Path2.Text = openFileDialog.SelectedPath;
}

 

2

在WPF中,使用Microsoft.Win32.OpenFileDialog只能选择文件,FolderBrowserDialog只能用树型的方式选择文件夹,很不好用.

终于找到一个办法,使用Windows API Code Pack

在VS里打开Package Manager Console后输入Install-Package WindowsAPICodePack-Shell获取包后

就可以像这样打开选择文件夹Dialog了:

 

using Microsoft.WindowsAPICodePack.Dialogs;

var dlg = new CommonOpenFileDialog();
dlg.IsFolderPicker = true;
dlg.InitialDirectory = currentDirectory;

if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
var folder = dlg.FileName;
}

保存文件

// 创建保存文件对话框
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = Path.GetFileName(fileUrl); // 设置默认文件名
saveFileDialog.DefaultExt = Path.GetExtension(fileUrl); // 设置默认扩展名
saveFileDialog.Filter = "所有文件 (*.*)|*.*"; // 过滤器

// 打开对话框
if (saveFileDialog.ShowDialog() == true)
{
string destinationFilePath = saveFileDialog.FileName;

}

posted @ 2021-02-19 17:06  simadi  阅读(5572)  评论(0)    收藏  举报