C#使用FolderBrowserDialog类实现选择打开文件夹方法详解_C#教程

分享到:

1.在C#中使用FolderBrowserDialog类,就可以实现选择文件夹的功能,并将所选择的的文件夹路径记录下来。

(1).首先先引入命名空间System.Windows.Forms;  
(2).然后在应用程序的主入口点,也就是static void Main()方法上面加上[STAThread]属性;


/// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

(3).然后定义我们的事件触发;


private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if(dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
            {
                path=dilog.SelectedPath;
            }
        }


(4).打开刚才我们所选择的文件夹;


private void button2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(path))
            {
                System.Diagnostics.Process.Start("Explorer.exe", path);
            }
            else
            {
                MessageBox.Show("请选择路径");
            }
        }

以上就完成了,选择文件夹的功能。

2.需要注意的是在程序的入口点出,需要添加[STAThread]属性,当然也可以不添加这个属性,但是需要开启另外一个线程来处理。代码如下所示:


private void button1_Click(object sender, EventArgs e)
        {
            Thread newThread = new Thread(new ThreadStart(TEST));
            newThread.SetApartmentState(ApartmentState.STA);
            newThread.Start();
            //或
            //Thread app = new Thread(new ParameterizedThreadStart(TEST));//两个TEST方法不一样,委托类型不一样
            //app.ApartmentState = ApartmentState.STA;
            //app.Start();

        }

        private void TEST(object obj)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if(dilog.ShowDialog() == DialogResult.OK)
            {
                path=dilog.SelectedPath;
            }

        }
        private void TEST()
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if (dilog.ShowDialog() == DialogResult.OK)
            {
                path = dilog.SelectedPath;
            }
        }

昵    称:
验证码:

相关文档: