Setting the initial directory of an SaveFileDialog?

前端 未结 14 2184
一个人的身影
一个人的身影 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条回答
  •  感情败类
    2020-12-01 11:02

    Just wanted to weigh in on this discussion (a couple of years too late) as I had exact problem too. Even though one is led to believe that this behavior - i.e using a default path the first time and then the previous selected path after that - can be achieved by using openFileDialog's properties and functions, one simply can't (per now)!

    One could change the working directory to the desired default path (e.g. Environment.CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);) but some framework, like Unity, doesn't like this very much and terminates.

    Because of this I ended up with this code:

    private bool firstDialogOpened = true;
    
    public void BrowseFiles()
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Model files (*.obj)|*.obj|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
    
        if (firstDialogOpened)
        {
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            firstDialogOpened = false;
        }
    
        if (openFileDialog.ShowDialog() == DialogResult.OK)
            filepath.text = openFileDialog.FileName;
    }
    

    This gives the desired behavior for me, although I would have loved a more elegant solution.

提交回复
热议问题