c# 对话框获取文件,文件夹和保存文件

1.获取文件

 1         /// <summary>
 2         /// 选择文件
 3         /// </summary>
 4         /// <returns>选择的文件路径</returns>
 5         private string GetFilePath()
 6         {
 7             var filePath = string.Empty;
 8             using (OpenFileDialog openFileDialog = new OpenFileDialog())
 9             {
10                 //打开时默认显示的路径
11                 openFileDialog.InitialDirectory = "C:\\";
12                 //选择的文件类型的筛选器
13                 openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
14                 //选择文件类型的索引,打开时默认什么类型,如本例中All files (*.*)|*.*"
15                 openFileDialog.FilterIndex = 2;
16 
17                 if (openFileDialog.ShowDialog() == DialogResult.OK)
18                 {
19                     //获取文件名
20                     filePath = openFileDialog.FileName;
21 
22                 }
23             }
24             return filePath;
25         }    

2.获取文件夹

 1         /// <summary>
 2         /// 获取文件夹
 3         /// </summary>
 4         /// <returns>选择的文件夹路径</returns>
 5         private string GetFolderPath()
 6         {
 7             string folderPath = string.Empty;
 8             using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
 9             {
10                 //对话框的标题
11                 folderBrowserDialog.Description = "选择文件夹";
12                 //显示对话框
13                 DialogResult dialogResult = folderBrowserDialog.ShowDialog();
14                 if (dialogResult == DialogResult.OK)
15                 {
16                     //获取选择的文件夹的路径
17                     folderPath = folderBrowserDialog.SelectedPath;
18                 }
19             };
20             return folderPath;
21         }    

3.保存文件

 1         /// <summary>
 2         /// 保存文件
 3         /// </summary>
 4         private void SaveFile()
 5         {
 6             SaveFileDialog saveFileDialog = new SaveFileDialog();
 7             //打开时默认显示的路径
 8             saveFileDialog.InitialDirectory = "C:\\";
 9             //选择的文件类型的筛选器
10             saveFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
11             //选择文件类型的索引,打开时默认什么类型,如本例中All files (*.*)|*.*"
12             saveFileDialog.FilterIndex = 2;
13 
14             if (saveFileDialog.ShowDialog() == DialogResult.OK)
15             {
16                 string fileName = saveFileDialog.FileName;
17                 FileStream fs = new FileStream(fileName, FileMode.Create);
18                 fs.Close();
19             }
20         }

 

posted @ 2021-04-21 18:32  一只年轻的小码熊  阅读(492)  评论(0)    收藏  举报