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

2023-12-02

据我们所知WPFOpenFileDialog不再更改应用程序的工作目录并且RestoreDirectory属性“未实现”。但是,在随后打开时,其初始目录默认为最后打开的文件而不是原始工作目录,因此此信息必须存储在某个地方。我想知道是否可以从用户代码获取/设置它?


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

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Comdlg32\OpenSaveMRU

该键下面是各种文件扩展名的子键(例如,exe, docx, py, etc).

现在,如果您想读取这些值,这将获得子项下存储的所有路径的列表(改编自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());
}

参考:

  • http://social.msdn.microsoft.com/Forums/zh/vcmfcatl/thread/bfd89fd3-8dc7-4661-9878-1d8a1bf62697
  • 获取文件打开对话框中最后打开的文件
  • http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/c43ddefb-1274-4ceb-9cda-c78d860b687c)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐