C#檔案夾選擇框的使用(C#選擇檔案夾,C# 開啟檔案夾,C# 瀏覽檔案夾,C#怎麼選擇檔案夾)

來源:互聯網
上載者:User

  今天在做報表統計的時候,遇到將報表產生到指定的位置去,在網上找了一些資料,整理了一下,分享一下。

  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;            }        }

 

     選擇檔案夾的Demo點擊此處下載。

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.