vs2008 winform  的工具箱中有两个组件:folderBrowserDialog与openFileDialog.他们的作用如下:
folderBrowserDialog:打开一个浏览对话框,以便选取路经.
openFileDialog: 打开一个浏览对话框,以便选取一个文件名.
 
在实际操作中的应用如下:
  private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            this.textBox1.Text = folderBrowserDialog1.SelectedPath;
        }
    private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            this.textBox2.Text = openFileDialog1.SafeFileName;
        }
 
如果没有在窗体中拖入folderBrowserDialog与openFileDialog组件,代码也可以这样来写:
using System.Collections.Generic;   
- using System.ComponentModel;   
- using System.Data;   
- using System.Drawing;   
- using System.Text;   
- using System.Windows.Forms;   
-   
- namespace WindowsApplication1   
- {   
-     public partial class SelectFolder : Form   
-     {   
-         public SelectFolder()   
-         {   
-             InitializeComponent();   
-         }   
-   
-         private void btnSelectPath_Click(object sender, EventArgs e)   
-         {   
-             FolderBrowserDialog path = new FolderBrowserDialog();   
-             path.ShowDialog();   
-             this.txtPath.Text = path.SelectedPath;   
-         }   
-   
-         private void btnSelectFile_Click(object sender, EventArgs e)   
-         {   
-             OpenFileDialog file = new OpenFileDialog();   
-             file.ShowDialog();   
-             this.txtFile.Text = file.SafeFileName;   
-         }   
-   
-     }   
- } 
 
 
 
 
 
最近寫winform的程式,剛好要用到這樣的功能
介紹如何利用FolderBrowserDialog與OpenFileDialog
來選擇目錄或檔案...
c#(winform)部分程式碼
SelectFolder.cs
| 01 | <span style="display: none"id="1226045165047S"> </span>usingSystem; | 
 
| 02 | usingSystem.Collections.Generic; | 
 
| 03 | usingSystem.ComponentModel; | 
 
| 07 | usingSystem.Windows.Forms; | 
 
| 09 | namespaceWindowsApplication1 | 
 
| 11 |     publicpartialclassSelectFolder : Form | 
 
| 15 |             InitializeComponent(); | 
 
| 18 |         privatevoidbtnSelectPath_Click(objectsender, EventArgs e) | 
 
| 20 |             FolderBrowserDialog path = newFolderBrowserDialog(); | 
 
| 22 |             this.txtPath.Text = path.SelectedPath; | 
 
| 25 |         privatevoidbtnSelectFile_Click(objectsender, EventArgs e) | 
 
| 27 |             OpenFileDialog file = newOpenFileDialog(); | 
 
| 29 |             this.txtFile.Text = file.SafeFileName; | 
 
 
 
 
執行結果:
 
1.主畫面
![]()
2.選目錄
![]()
3.選檔案
![]()
參考網址:
http://www.codeproject.com/KB/cs/csFolderBrowseDialogEx.aspx