C#打开选择文件对话框和选择目录对话框
1.选择文件对话框
首先引用using Microsoft.Win32名称空间。
private void BrowseButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); if(dialog.ShowDialog(this)== true) { LocationBox.Text = dialog.FileName; } }
2.选择目录对话框,利用winForm库
引用using System.Windows.Forms;如果找不到此名称空间,右键项目-添加-引用-程序集里面寻找并添加。
private void DisplayButton_Click(object sender, RoutedEventArgs e) { try { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择文件路径"; DialogResult result = dialog.ShowDialog(); if(result == System.Windows.Forms.DialogResult.Cancel) { return; } string folderPath = dialog.SelectedPath.Trim(); DirectoryInfo theFolder = new DirectoryInfo(folderPath); if (theFolder.Exists) { //操作 return; }
C#通用选择文件对话框
通用选择文件对话框封装
/// <summary> /// 文件选择通用对话框 /// </summary> public class FilesSelectDialog { public OpenFileDialog fileDialog; //默认打开路径 public string DirPath = "D:\\"; public string FilePath; public string Title; public string Filter= "图片(*.jpg,*.jpge,*.bmp,*.png)|*.jpg;*.jpge;*.bmp;*.png| 所有文件(*.*) |*.*"; public FilesSelectDialog(string title) { Title = title; fileDialog = new OpenFileDialog();//打开文件对话框 } public bool Show() { fileDialog.InitialDirectory = DirPath;//初始化路径 fileDialog.Filter = Filter;//过滤选项设置,文本文件,所有文件。 fileDialog.FilterIndex = 0;//当前使用第二个过滤字符串 fileDialog.RestoreDirectory = true;//对话框关闭时恢复原目录 fileDialog.Title = Title; if (fileDialog.ShowDialog() == DialogResult.OK) { //for (int i = 1; i <= fileDialog.FileName.Length; i++) //{ // if (fileDialog.FileName.Substring(fileDialog.FileName.Length - i, 1).Equals(@"\")) // { // //更改默认路径为最近打开路径 // Path = fileDialog.FileName.Substring(0, fileDialog.FileName.Length - i + 1); // return true; // } //} FilePath = fileDialog.FileName; try { DirPath = System.IO.Path.GetDirectoryName(FilePath);//更改默认路径为最近打开路径 } catch (Exception) { return false; } return true; } else { return false; } } } FilesSelectDialog selectDialog = new FilesSelectDialog("请选择要转换的图片"); private void Btn_OpenImsge_Click(object sender, EventArgs e) { //FilesSelectDialog selectDialog = new FilesSelectDialog("请选择要转换的图片"); selectDialog.Filter = "图片(*.jpg,*.jpge,*.bmp,*.png)|*.jpg;*.jpge;*.bmp;*.png| 所有文件(*.*) |*.*"; if (selectDialog.Show()==true) { SourceSrcBox.Text = selectDialog.FilePath; //MessageBox.Show(selectDialog.FilePath); DisplayImage(SourceSrcBox.Text); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持寻技术。