C# 设置 SaveFileDialog 的初始目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1175242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:02:46  来源:igfitidea点击:

Setting the initial directory of an SaveFileDialog?

c#.netwpfwinapi

提问by tom greene

I'd like a SaveFileDialog with the following behavior:

我想要一个具有以下行为的 SaveFileDialog:

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

  • Afterwards, it goes to the last selected folder. What's the best way to accomplish this?

  • 第一次打开它时,它会转到“我的文档”。

  • 之后,它会转到最后选择的文件夹。实现这一目标的最佳方法是什么?

If I don't set the InitialDirectory, it goes to the exe's directory - which is not what I want. It rememebers the last selected directory though - even between executions.

如果我不设置 InitialDirectory,它会进入 exe 的目录 - 这不是我想要的。它记得最后选择的目录 - 即使在执行之间也是如此。

If I set the InitialDirectory, it does not remember the last selected directory. Of course, I could save the last selected directory in the registry :( but I am looking for a better solution.

如果我设置了 InitialDirectory,它就不会记住上次选择的目录。当然,我可以将最后选择的目录保存在注册表中 :( 但我正在寻找更好的解决方案。

      SaveFileDialog dialog = new SaveFileDialog();
      //??? dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      dialog.ShowDialog();

Any advice?

有什么建议吗?

采纳答案by Andrew Hare

You need to set the RestoreDirectoryto trueas well as the InitialDirectoryproperty.

您需要设置RestoreDirectorytotrue以及InitialDirectory属性。

回答by Icono123

I did some testing with .NET 2.0 and it seems if I set FileName to anything other than a literal string it doesn't work. When I use a method or accesstor to set the property the initial directory is ignored.

我用 .NET 2.0 做了一些测试,似乎如果我将 FileName 设置为文字字符串以外的任何内容,它就不起作用。当我使用方法或访问器来设置属性时,初始目录将被忽略。

回答by Jeffrey Harmon

I have no idea why this works, but I was finally able to get it working for me.

我不知道为什么这有效,但我终于能够让它为我工作。

I found that if I gave the full path, it would not work, but if I put that full path inside of Path.GetFullPath(), then it would work. Looking at the before and after values show them being the same, but it would consistently not work without it, and work with it.

我发现,如果我提供完整路径,它将不起作用,但如果我将该完整路径放在Path.GetFullPath() 中,则它会起作用。查看之前和之后的值表明它们是相同的,但如果没有它,它将始终无法工作,并且可以使用它。

//does not work
OpenFileDialog dlgOpen = new OpenFileDialog();
string initPath = Path.GetTempPath() + @"\FQUL";
dlgOpen.InitialDirectory = initPath;
dlgOpen.RestoreDirectory = true;

//works
OpenFileDialog dlgOpen = new OpenFileDialog();
string initPath = Path.GetTempPath() + @"\FQUL";
dlgOpen.InitialDirectory = Path.GetFullPath(initPath);
dlgOpen.RestoreDirectory = true;

回答by mousio

I too have tried different "solutions" found in different places, but none of them seem to work as soon as there is an MRU list entry in the registry :/ But here is my own simple workaround…

我也尝试过在不同地方找到的不同“解决方案”,但是一旦注册表中有 MRU 列表条目,它们似乎都不起作用:/但这是我自己的简单解决方法......

Instead of setting the dialog's InitialDirectoryproperty, set the FileNameproperty to your path, but combined with the selected Filter, e.g.:

不是设置对话框的InitialDirectory属性,而是将属性设置FileName为您的路径,但与 selected 相结合Filter,例如:

dialog.FileName = Path.Combine(myPath, "*.*");

回答by user1956901

Make sure to check that the directory path exists before setting the Initial directory property. Create the directory if it does not exist. ie

在设置初始目录属性之前,请确保检查目录路径是否存在。如果目录不存在,则创建该目录。IE

if (!Directory.Exists(FooDirectory))
{
     Directory.CreateDirectory(FooDirectory);
}

回答by Ali Akbar

If you use forward slash anywhere in your path, InitialDirectory does not work. Make sure they are converted to back slashes

如果您在路径中的任何位置使用正斜杠,InitialDirectory 将不起作用。确保它们被转换为反斜杠

回答by PauLEffect

savefiledialog.InitialDirectory = Application.StartupPath;
savefiledialog.RestoreDirectory = true;

tested a second ago.

一秒钟前测试。

回答by OhBeWise

None of the provided solutions worked for me sadly.

可悲的是,提供的解决方案都没有对我有用。

In addition to the OP specifications, I wanted the program to remember the last save location between runs. For this, in the Visual Studios Solution Explorer under ProjectName -> Properties -> Settings.settings, I setup the following property:

除了 OP 规范之外,我还希望程序记住两次运行之间的最后保存位置。为此,在 Visual Studios 解决方案资源管理器下ProjectName -> Properties -> Settings.settings,我设置了以下属性:

Settings.settings property: Name=PreviousPath, Type=string, Scope=User, leave Value empty

Settings.settings 属性:Name=PreviousPath,Type=string,Scope=User,将 Value 留空

Because I am keeping the SaveFileDialogaround for the duration of the program's running, I instantiate at the start. Then in the Commandfor bringing up the dialog:

因为我SaveFileDialog在程序运行期间一直在附近,所以我在开始时实例化。然后在Command弹出对话框中:

if (string.IsNullOrEmpty(Settings.Default.PreviousPath))
{
    this.saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
else
{
    this.saveDialog.InitialDirectory = Settings.Default.PreviousPath;
}

this.saveDialog.FileName = "Default_File_Name";

bool result = this.saveDialog.ShowDialog() ?? false;

if (result)
{
    Settings.Default.PreviousPath = Path.GetDirectoryName(this.saveDialog.FileName);
    Settings.Default.Save();

    // Code writing to the new file...
}

This gives the behavior:

这给出了行为:

  • First time the program is run and dialog is opened, it navigates to "My Documents".
  • Consecutive runs and dialog opened:
    • If saved on a previous open, it navigates to previous save location.
    • If not saved on a previous open, navigates to "My Documents".
  • 第一次运行程序并打开对话框时,它导航到“我的文档”。
  • 连续运行并打开对话框:
    • 如果保存在上一次打开时,它会导航到上一次保存位置。
    • 如果上次打开时未保存,请导航到“我的文档”。

回答by danio

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

建议的解决方法对我不起作用,所以在找到WPF OpenFileDialog 如何跟踪上次打开文件的目录之后?我实施了:

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.

如果此文件扩展名之前未使用该对话框,则将使用提供的 initialDirectory。使用对话框后,它将恢复为记住上一个目录的默认行为。

回答by user104933

I found that setting InitialDirectoryto nullfirst works around user history.

我发现设置InitialDirectorynullfirst 可以解决用户历史记录。

    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.InitialDirectory = null;
    dlgOpen.InitialDirectory = @"c:\user\MyPath";