WPF OpenFileDialog如何跟踪上次打开文件的目录?

NS.*_*.X. 2 openfiledialog working-directory

我们知道WPF OpenFileDialog不再更改应用程序的工作目录和RestoreDirectory属性"未实现".但是,在后续打开时,其初始目录默认为最后打开的文件而不是原始工作目录,因此必须将此信息存储在某处.我想知道是否可以从用户代码中获取/设置它?

nic*_*k_w 5

在Windows 7上,最近的文件信息存储在注册表中的此键:

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Comdlg32\OpenSaveMRU
Run Code Online (Sandbox Code Playgroud)

下面这个键是各种文件扩展子项(如exe,docx,py,等).

现在,如果您想要读取这些值,这将获得存储在子键下方的所有路径的列表(从此处改编):

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());
}
Run Code Online (Sandbox Code Playgroud)

参考文献: