To open files in your WPF application, you can use the managed wrapper class OpenFileDialog, which is present under the Microsoft.Win32 namespace. You just have to create the instance and call the ShowDialog() method by optionally setting a few properties for UI customization.
A basic open file dialog looks like the following screenshot, providing you with an option to select one or more files to open:
The following code snippet demonstrates how to initiate the open file dialog by optionally filling the file-extension filter:
private void OnOpenButtonClicked(object sender, RoutedEventArgs e) { var openfileDialog = new OpenFileDialog { Filter = "Text documents (.txt) | *.txt | Log files (.log) |
*.log" }; var dialogResult = openfileDialog.ShowDialog(); if (dialogResult == true) { var fileName = openfileDialog.FileName; } }
The dialogResult returned by the ShowDialog() method tells us whether the operation was performed successfully. Based on that, you can call the instance of the file dialog to get more details about the selected file.