WPF – Limit OpenFileDialog folder tree to a certain folder
Starting with .NET 8, you can constrain the OpenFileDialog
and OpenFolderDialog
folder tree to a given root folder. You can do so by setting the RootDirectory
property on the dialog before calling ShowDialog()
.
It’s very important to note that this does not limit the selection and the navbar navigation in any way. The user will still be able to navigate to folders outside the specificied RootDirectory
. The same goes for the InitialDirectory
property which you can set to any folder you’d like outside the RootDirectory
.
Let’s look at an example:
var dialog = new OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
RootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
};
dialog.ShowDialog();
Code language: C# (cs)
This will show an open file dialog focused on the MyDocuments
folder, while it’s folder tree on the left will be scoped to the specified root directory – in this case, MyPictures
.
One Comment