使用注册表来记录文件夹对话框的打开路径

      C#中的FolderBrowserDialog有个RootFolder属性,每次打开文件夹对话框默认指向的就是这个目录。但如果我们需要频繁打开同一个目录,则可以在ShowDialog()函数执行前,对SelectedPath属性赋值,这在程序退出前都有效,如果想要程序下次运行还是打开这个目录,则需要将打开的路径记录下来。可以使用两种方法:一、使用文件记录;二、使用注册表。

      使用文件记录有一个不好的地方,就是除了可执行程序exe外,还必须有一个配置文件,用户是可知的,这样非常的不好。使用注册表则没有这种烦恼。其使用方法如下:

      //在构造函数执行

try
{

    RegistryKey testKey = Registry.CurrentUser.OpenSubKey("TestKey");
    if (testKey == null)
    {
        testKey = Registry.CurrentUser.CreateSubKey("TestlKey");
        testKey.SetValue("OpenFolderDir", "");
        testKey.Close();
        Registry.CurrentUser.Close();
    }
    else
    {
        defaultfilePath = testKey.GetValue("OpenFolderDir").ToString();
        testKey.Close();
        Registry.CurrentUser.Close();
    }
}
catch (Exception e)
{
}

      

       //在ShowDialog()执行前执行

        if (defaultfilePath != "")  
       {  
             //设置此次默认目录为上一次选中目录                  
             dlg.SelectedPath = defaultfilePath;  
       }  

//在ShowDialog()返回Ok时执行

if (defaultfilePath != dlg.SelectedPath)
{
      defaultfilePath = dlg.SelectedPath;
      RegistryKey testKey = Registry.CurrentUser.OpenSubKey("TestKey",true);  //true表示可写,false表示只读
      testKey.SetValue("OpenFolderDir", defaultfilePath);
      testKey.Close();
      Registry.CurrentUser.Close();
}

原文地址:https://www.cnblogs.com/BensonHe/p/1784432.html