Reputation: 1886
In my application I use both OpenFileDialog
and FolderBrowserDialog
on button click handlers:
var fileDialog = new System.Windows.Forms.OpenFileDialog();
var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
Strange thing is that when calling OpenFileDialog
it starts in explorer from folder in which file was chosen last time.
But FolderBrowserDialog
opens MyComputer each time in explorer no matter what folder was chosen last time. How can I get same behavior (remembering last chosen folder) for `FolderBrowserDialog'?
It's also interesting where 'OpenFileDialog' stores folder of last chosen file? Does windows stores it for each application?
Upvotes: 1
Views: 1269
Reputation: 28272
You can set FolderBrowserDialog
's selected folder using the SelectedPath
property before opening:
var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
folderDialog.RootFolder = System.Environment.SpecialFolder.MyComputer;
folderDialog.SelectedPath = <variable_where_you_stored_the_last_path>;
For example:
private string _lastFolderDialog = null;
// ...
var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
folderDialog.SelectedPath = _lastFolderDialog;
if(folderDialog.ShowDialog() == DialogResult.OK)
{
_lastFolderDialog = folderDialog.SelectedPath;
}
As for the OpenFileDialog
, I think you mean:
fileDialog.InitialDirectory =
Environment.GetFolderPath(System.Environment.SpecialFolder.MyComputer);
However that won't work, since MyComputer
doesn't have a path. Try this instead:
fileDialog.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
You can check for other CLSIDs in the registry under HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CLSID
As you have already discovered, if InitialDirectory
is set to null
, it'll remember the last opened folder. This won't happen with FolderBrowserDialog
though
All that said, and as I stated in the comments, the FolderBrowserDialog
is pretty much obsolete and you should not use it at all. According to the MSDN for the native API (SHBrowseForFolder
) that supports it:
For Windows Vista or later, it is recommended that you use IFileDialog with the FOS_PICKFOLDERS option rather than the SHBrowseForFolder function. This uses the Open Files dialog in pick folders mode and is the preferred implementation.
You may want to check this question (which in turn links to this page) or this other question on how to implement IFileDialog
with FOS_PICKFOLDERS
in .NET
Upvotes: 5