Setting the initial directory of an SaveFileDialog?

前端 未结 14 2167
一个人的身影
一个人的身影 2020-12-01 10:05

I\'d like a SaveFileDialog with the following behavior:

  • The first time you open it, it goes to \"My Documents\".

  • Afterwards, it goes to the

14条回答
  •  猫巷女王i
    2020-12-01 11:01

    The suggested workarounds didn't work for me, so after finding How does WPF OpenFileDialog track directory of last opened file? I implemented:

    public static void SetInitialDirectory(this FileDialog dlg, string fileExtension, string initialDirectory)
            {
                // RestoreDirectory doesn't seem to be implemented - https://stackoverflow.com/questions/11144770/how-does-wpf-openfiledialog-track-directory-of-last-opened-file
                // so manually only set InitialDirectory if nothing is stored
                try
                {
                    var mru = @"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSavePidlMRU\" + fileExtension;
                    var rk = Registry.CurrentUser.OpenSubKey(mru);
                    if (rk == null)
                    {
                        dlg.InitialDirectory = initialDirectory;
                    }
                }
                catch (Exception)
                {
                    // SecurityException, ObjectDisposedException => allow default behaviour
                }
            }
    

    This will use the provided initialDirectory if the dialog has not been used before for this file extension. Once the dialog has been used, it reverts to the default behaviour of remembering the previous directory.

提交回复
热议问题