今天在做報表統計的時候,遇到將報表生成到指定的位置去,在網上找了一些資料,整理了一下,分享一下。
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點擊此處下載。