问题
As we know WPF OpenFileDialog
no more changes the app's working directory and RestoreDirectory
property is "unimplemented". However, upon subsequent open, its initial directory is default to the last opened file rather than the original working directory, so this information must be stored somewhere. I wonder is it possible to get/set it from user code?
回答1:
On Windows 7 the recent file information is stored in the registry at this key:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Comdlg32\OpenSaveMRU
Beneath this key are subkeys for the various file extensions (e.g., exe
, docx
, py
, etc).
Now, if you want to read these values, this will get a list of all paths stored beneath the subkeys (adapted from here):
String mru = @"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSavePidlMRU";
RegistryKey rk = Registry.CurrentUser.OpenSubKey(mru);
List<string> filePaths = new List<string>();
foreach (string skName in rk.GetSubKeyNames())
{
RegistryKey sk = rk.OpenSubKey(skName);
object value = sk.GetValue("0");
if (value == null)
throw new NullReferenceException();
byte[] data = (byte[])(value);
IntPtr p = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, p, data.Length);
// get number of data;
UInt32 cidl = (UInt32)Marshal.ReadInt16(p);
// get parent folder
UIntPtr parentpidl = (UIntPtr)((UInt32)p);
StringBuilder path = new StringBuilder(256);
SHGetPathFromIDListW(parentpidl, path);
Marshal.Release(p);
filePaths.Add(path.ToString());
}
References:
- http://social.msdn.microsoft.com/Forums/zh/vcmfcatl/thread/bfd89fd3-8dc7-4661-9878-1d8a1bf62697
- Getting the last opened file in fileopen dialog box
- http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/c43ddefb-1274-4ceb-9cda-c78d860b687c)
来源:https://stackoverflow.com/questions/11144770/how-does-wpf-openfiledialog-track-directory-of-last-opened-file