1.OpenFileDialog
1 private void btnOpen_Click(object sender, EventArgs e) 2 { 3 OpenFileDialog ofd = new OpenFileDialog(); 4 ofd.InitialDirectory = @"C:\Users\LWP1398\Desktop"; //设置初始路径 5 ofd.Filter = "Excel文件(*.xls)|*.xls|Csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //设置“另存为文件类型”或“文件类型”框中出现的选择内容 6 ofd.FilterIndex = 2; //设置默认显示文件类型为Csv文件(*.csv)|*.csv 7 ofd.Title = "打开文件"; //获取或设置文件对话框标题 8 ofd.RestoreDirectory = true; 9 if (ofd.ShowDialog() == DialogResult.OK) 10 { 11 //FileName:所选文件的全路径 SafeFileName:所选的文件名 12 txtPath.Text = "FileName:" + ofd.FileName + "\r\n" + "SafeFileName:" + ofd.SafeFileName; 13 } 14 }
2.OpenFileDialog选择多个文件
1 private void button3_Click(object sender, EventArgs e) 2 { 3 OpenFileDialog ofd = new OpenFileDialog(); 4 ofd.InitialDirectory = @"C:\Users\LWP1398\Desktop"; //设置初始路径 5 ofd.Filter = "Excel文件(*.xls)|*.xls|Csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //设置“另存为文件类型”或“文件类型”框中出现的选择内容 6 ofd.FilterIndex = 2; //设置默认显示文件类型为Csv文件(*.csv)|*.csv 7 ofd.Title = "打开文件"; //获取或设置文件对话框标题 8 ofd.RestoreDirectory = true;////设置对话框是否记忆上次打开的目录 9 10 ofd.Multiselect = true;//设置多选 11 if (ofd.ShowDialog() == DialogResult.OK) 12 { 13 for (int i = 0; i < ofd.FileNames.Length; i++) 14 { 15 txtPath.Text += ofd.FileNames[i] + "\r\n";//输出一个路径回车换行 16 } 17 for (int i = 0; i < ofd.FileNames.Length; i++) 18 { 19 txtPath.Text += ofd.SafeFileNames[i] + "\r\n"; 20 } 21 } 22 }
3.SaveFileDialog
1 private void button2_Click(object sender, EventArgs e) 2 { 3 SaveFileDialog sfd=new SaveFileDialog(); 4 sfd.Filter = "文本文件(*.txt)|*.txt|所有文件|*.*";//设置文件类型 5 sfd.FileName = "保存";//设置默认文件名 6 sfd.DefaultExt = "txt";//设置默认格式(可以不设) 7 sfd.AddExtension = true;//设置自动在文件名中添加扩展名 8 if (sfd.ShowDialog()==DialogResult.OK) 9 { 10 txtPath.Text = "FileName:" + sfd.FileName + "\r\n" ; 11 using (StreamWriter sw = new StreamWriter(sfd.FileName)) 12 { 13 sw.WriteLineAsync("今天是个好天气"); 14 } 15 } 16 MessageBox.Show("ok"); 17 }
时间: 2024-11-06 03:51:30