This is a simple example to have an OpenFileDialog (a premade view done by Windows to select a file to open) with WPF, filtering on XLSX file:
var openFileDialog = new OpenFileDialog
{
Filter = "Excel files(*.xlsx)|*.xlsx|All files(*.*)|*.* ",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string fullFileName = openFileDialog.FileName;
System.Windows.Forms.MessageBox.Show($"Selected file is {fullFileName}", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Code language: C# (cs)
In this case the InitialDirectory will always exist because it is the Desktop of the current user. But you have to know that if the targeted InitialDirectory doesn’t exist, then the OpenFileDialog will not show up.
Another point of attention is the fact that no space will be allowed around the pipes (“|”) otherwise the filtering will simply not work.
So this is ok: “Excel files(*.xlsx)|*.xlsx”
But this is not: “Excel files(*.xlsx) | *.xlsx”
Have a look at my other post about how to keep a dialog on top of another view.
Happy coding! 🙂
[…] using a Microsoft.Win32 Dialog (OpenDialog or SaveDialog), it is possible that it will be opened behind the Main Window. So a good way to go […]