1、选择文件用OpenDialog
OpenFileDialog dialog = new OpenFileDialog(); dialog.Multiselect = true;//该值确定是否可以选择多个文件 dialog.Title = "请选择文件夹"; dialog.Filter = "所有文件(*.*)|*.*"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string file = dialog.FileName; }
Filter 属性 赋值为一字符串 用于过滤文件类型; 字符串说明如下: ‘|’分割的两个,一个是注释,一个是真的Filter,显示出来的是那个注释。如果要一次显示多中类型的文件,用分号分开。 如: Open1.Filter="图片文件(*.jpg,*.gif,*.bmp)|*.jpg;*.gif;*.bmp"; 则过滤的文件类型为 “|”号 右边的 *.jpg;*.gif;*.bmp 三种类型文件,在OpenDialog/SaveDialog中显示给用户看的文件类型字符串则是 :“|”号 左边的 图片文件(*.jpg,*.gif,*.bmp)。 再如: Open1.Filter="图像文件(*.jpg;*.jpg;*.jpeg;*.gif;*.png)|*.jpg;*.jpeg;*.gif;*.png";
2、使用System.Windows.Forms.FolderBrowserDialog选择文件夹
System.Windows.Forms.FolderBrowserDialog dialog =new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "请选择Txt所在文件夹"; if (dialog.ShowDialog()==System.Windows.Forms.DialogResult.OK ) { if (string.IsNullOrEmpty(dialog.SelectedPath)) { System.Windows.MessageBox.Show(this, "文件夹路径不能为空", "提示"); return; } this.LoadingText = "处理中..."; this.LoadingDisplay = true; Action<string> a = DaoRuData; a.BeginInvoke(dialog.SelectedPath,asyncCallback, a); }
3、直接打开某路径下的文件或者文件夹
System.Diagnostics.Process.Start("ExpLore", "C:\\window");
实现的代码如下: public void openfile(int n) { OpenFileDialog openfile = new OpenFileDialog(); openfile.Filter = "*.cs | *.cs";//设置文件后缀 if (openfile.ShowDialog() == DialogResult.OK) { string filename = openfile.FileName; dic1.Add(n, filename); fileArr[n].Text = filename.Substring(filename.LastIndexOf("\\") + 1, filename.LastIndexOf(".") - (filename.LastIndexOf("\\") + 1)); } } 页面中的【NO】按钮是用来打开文件的,打开的文件是readonly权限,是不可编写的,点击【编辑】按钮就可以打开文件并且编辑,实现代码如下: public void readfile(int btNumber, string mode)//点击【NO】按钮,以只读发方式打开文件 { int key = Convert.ToInt16(numArr[btNumber].Text) - 1; foreach (KeyValuePair<int, string> kv in dic1) { if (kv.Key == key) { System.IO.FileInfo f = new System.IO.FileInfo(kv.Value); if (mode == "ReadOnly") { f.Attributes = System.IO.FileAttributes.ReadOnly; } System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); } } } public void readfile(int btNumber)//点击【编辑】按钮,以可读可写发方式打开文件 { int key = Convert.ToInt16(numArr[btNumber].Text) - 1; foreach (KeyValuePair<int, string> kv in dic1) { if (kv.Key == key) { System.IO.FileInfo f = new System.IO.FileInfo(kv.Value); f.Attributes = System.IO.FileAttributes.Normal; System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); } } } 在C#窗体中使用代码实现文件的打开,用的是进程的思想,即Windows中每个软件都是一个进程,我们平时在电脑中自己打开一个txt文件就是打开一个进程,在代码中同样可以实现打开文件的功能。 关键语句就是: System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); 这里的kv.Value是用键值对把文件名和【NO】中的序号对应起来,方便做一些读写操作。 在没有设置文件的权限时,文件是不可改变的,所以以上代码中,如果不实现 f.Attributes = System.IO.FileAttributes.ReadOnly; 文件打开后也是不能更改的,大家可以试试。 为了使文件能够修改,要设置成 f.Attributes = System.IO.FileAttributes.Normal; 设置文件的属性主要用到了FileInfo类的Attributes属性。