C USES the FolderBrowserDialog class to implement the select open folder method
- 2020-05-26 09:58:59
- OfStack
1. You can use the FolderBrowserDialog class in C# to select folders and record the path to the selected folders.
(1). First, the namespace System.Windows.Forms is introduced;
(2). Then add the [STAThread] attribute to the main entry point of the application, which is the static void Main() method;
/// <summary>
/// The application's main entry point.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
(3). Then define our event trigger;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dilog = new FolderBrowserDialog();
dilog.Description = " Please 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("Explorer.exe", path);
}
else
{
MessageBox.Show(" Please select the path ");
}
}
So that's it. Select folder.
2. It should be noted that you need to add the [STAThread] property at the entry point of the program. Of course, you can not add this property, but you need to open another thread for processing. The code is as follows:
private void button1_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));// two TEST Method is not 1 Like, the delegate type is not 1 sample
//app.ApartmentState = ApartmentState.STA;
//app.Start();
}
private void TEST(object obj)
{
FolderBrowserDialog dilog = new FolderBrowserDialog();
dilog.Description = " Please select folder ";
if(dilog.ShowDialog() == DialogResult.OK)
{
path=dilog.SelectedPath;
}
}
private void TEST()
{
FolderBrowserDialog dilog = new FolderBrowserDialog();
dilog.Description = " Please select folder ";
if (dilog.ShowDialog() == DialogResult.OK)
{
path = dilog.SelectedPath;
}
}