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

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

本文介绍了WPF OpenFileDialog如何跟踪上次打开的文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

On Windows 7 the recent file information is stored in the registry at this key:

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

此键下方是各种文件扩展名(例如exedocxpy等)的子项.

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());
}

参考文献:

  • 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)

这篇关于WPF OpenFileDialog如何跟踪上次打开的文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 08:29