How does WPF OpenFileDialog track directory of las

2020-04-16 17:28发布

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条回答
三岁会撩人
2楼-- · 2020-04-16 17:54

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:

查看更多
登录 后发表回答