调出文件浏览器窗口,用于选定文件。
代码模式下新建一个OpenFileDialog并设定相关属性
1
//打开一个文件选择框 OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Excel文件"; //文件浏览器的标题 ofd.FileName = ""; //默认文件名框中的默认名字 ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹,可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举,其中可以定义要返回路径的哪个系统目录 ofd.Filter = "Excel文件(*.xls)|*.xls"; //限制文件类型的方位,如果多个,例如:Excel文件(97-03)|*.xls|Excel文件(07以上版本)|*.xlsx ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名 ofd.CheckFileExists = true; //验证路径有效性 ofd.CheckPathExists = true; //验证文件有效性
2取得选择的文件的路径。
if (openFileDialog1.ShowDialog() == DialogResult.OK) { xlsPath = openFileDialog1.FileName; label1.Text = xlsPath; } else { label1.Text = "错了"; return; }