We know that C # contains a dialog box Control for selecting files, but does not have a dialog box Control for selecting folders. Many people have to use the TreeView class to select a folder, in fact, C # does not need to be so troublesome. We can use the FolderBrowser class of the FolderNameEditor class of C # To obtain the browsing folder dialog box function.
Let's take a look at how it is implemented.
Create a winform project and a new Class File (File-> AddNewItem-> Class ).
Because FolderNameEditor is in System. windows. forms. under the Design namespace, this namespace is located in the dynamic link library system. design. dll, so we need to add a new reference System in the solution. design. Then add the following in the Code:
Using System. Windows. Forms. Design;
Next, we create a new FolderDialog class, which inherits from the FolderNameEditor class and creates a new FolderBrowser class instance in this class. The DisplayDialog (string description) function is used to set the properties of the Instance fDialog and display the Browse folder dialog box. To obtain the folder Path, set a Path attribute and return the Path of the selected folder.
The Code is as follows:
Public class FolderDialog: FolderNameEditor
{
FolderNameEditor. FolderBrowser fDialog = new
System. Windows. Forms. Design. FolderNameEditor. FolderBrowser ();
Public FolderDialog ()
{
}
Public DialogResult DisplayDialog ()
{
Return DisplayDialog ("select a folder ");
}
Public DialogResult DisplayDialog (string description)
{
FDialog. Description = description;
Return fDialog. ShowDialog ();
}
Public string Path
{
Get
{
Return fDialog. DirectoryPath;
}
}
~ FolderDialog ()