I am unable to use the Win32 OpenFileDialog class
I tried the sample code below, which I copy-pasted straight from the Microsoft Documentation into my method, but I got error CS0246, because the compiler could not find OpenFileDialog.
I tried to add a reference to Win32, but it is nowhere to be found.
BTW, I did try to use the .NET OpenFileDialog and FolderBrowserDialog classes, but they cannot open a folder with a start location and that option is absolutely necessary to my application.
What did I do wrong ?
Here's my code.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
EDIT : PROBLEM SOLVED (solution below)
The bug came from the form designer. I initially dropped a FolderBrowserDialog object in my form. By default Visual Studio 2015 creates an object with RootFolder set to Desktop. Now, even if you set SelectedPath to your target folder, FolderBrowserDialog would still open the desktop folder instead of it.
So I instantiated a FolderBrowserDialog object inside my event handler and set SelectedPath to my target folder leaving RootFolder unset. And it now works like a charm.
private void B_Browse_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.SelectedPath = MyTargetFolder;
DialogResult result = fbd.ShowDialog();
// do stuff
}
Thanks everybody and have a good day :)