During report statistics today, I found some information on the Internet, sorted it out, and shared it.
1. Use the folderbrowserdialog class in C # To select a folder and record the selected folder path.
(1) first introduce the namespace system. Windows. forms;
(2). Add the [stathread] attribute to the main entry point of the application, that is, the static void main () method;
/// <Summary> /// main entry point of the application. /// </Summary> [stathread] Static void main () {application. enablevisualstyles (); application. setcompatibletextrenderingdefault (false); application. Run (New form1 ());}
(3). then define the event trigger;
Private void button1_click (Object sender, eventargs e) {folderbrowserdialog dilog = new folderbrowserdialog (); dilog. description = "select folder"; if (dilog. showdialog () = dialogresult. OK | dilog. showdialog () = dialogresult. yes) {Path = dilog. selectedpath ;}}
(4) Open the folder we just selected;
Private void button2_click (Object sender, eventargs e) {If (! String. isnullorempty (PATH) {system. Diagnostics. process. Start ("assumer.exe", PATH) ;}else {MessageBox. Show ("select path ");}}
The preceding figure shows how to select a folder.
2. Note that the [stathread] attribute needs to be added at the entry point of the program. Of course, this attribute can not be added, but another thread must be enabled for processing. The Code is as follows:
Private void button#click (Object sender, eventargs e) {thread newthread = new thread (New threadstart (TEST); newthread. setapartmentstate (apartmentstate. sta); newthread. start (); // or // thread APP = new thread (New parameterizedthreadstart (TEST); // the two test methods are different, and the delegate type is different. // app. apartmentstate = apartmentstate. sta; // app. start ();} private void test (Object OBJ) {folderbrowserdialog dilog = new folderbrowserdialog (); dilog. description = "select folder"; if (dilog. showdialog () = dialogresult. OK) {Path = dilog. selectedpath ;}} private void test () {folderbrowserdialog dilog = new folderbrowserdialog (); dilog. description = "select folder"; if (dilog. showdialog () = dialogresult. OK) {Path = dilog. selectedpath ;}}
Select the demo of the folder and click here to download it.