Folder Browser Dialog on Windows with C#
How to select or open folder on Windows with C# UI
In this guide, I’ll walk you through the process of implementing a folder selection UI using C#.
In many applications, users need to specify a folder where certain files will be saved or retrieved. Providing a user-friendly way to select folders enhances the overall usability of your application.
To implement a folder selection dialog in C#, we’ll use the FolderBrowserDialog
class provided by the .NET framework.
This class allows users to browse and select folders from their file system with ease.
The Code
Let’s dive into the code. Below is a simple C# method that displays a folder selection dialog and returns the path of the selected folder:
This method, ShowFolderBrowserDialogAsync
, can be called asynchronously to display the folder selection dialog. It returns a Task<string>
representing the path of the selected folder.
You can also call it synchronously with the ShowFolderBrowserDialog
function.
How to Use
Now that we have our method defined, let’s see how we can use it in our C# application.
Please note if you’re using WPF, you need to add a reference to System.Windows.Forms
.
Asynchronous Usage
In this example, we call ShowFolderBrowserDialogAsync
asynchronously to display the folder selection dialog.
Once the user selects a folder and clicks OK, the selected folder path is returned, and we print it out to the console.
Synchronous Usage
Alternatively, if you prefer synchronous code, you can use the following approach:
Here, we call the ShowFolderBrowserDialog
method synchronously.
It performs the same function as its asynchronous counterpart but without the need for async
and await
.
Conclusion
In this tutorial, we’ve learned how to implement a folder selection UI in C# using the FolderBrowserDialog
class.
Whether you prefer asynchronous or synchronous code, you can easily integrate this functionality into your C# applications to provide a seamless user experience when selecting folders.
Happy coding!
References
- c# - How do I use OpenFileDialog to select a folder? - Stack Overflow