Setting the initial directory of an SaveFileDialog?

前端 未结 14 2085
一个人的身影
一个人的身影 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:04

    This is what I ended up with, that goes along with where the OP wanted to point their dialog:

    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
    dlg.InitialDirectory = null;
    
    // May or may not want "saves", but this shows how to append subdirectories
    string path = (Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "My Documents") + "\\saves\\");  
    
    if (!Directory.Exists(path))
        Directory.CreateDirectory(path);
    
    dlg.InitialDirectory = path;
    dlg.RestoreDirectory = true;
    
    if (dlg.ShowDialog().Value == true)
    {
        // This is so you can have JUST the directory they selected
        path = dlg.FileName.Remove(dlg.FileName.LastIndexOf('\\'), dlg.FileName.Length - dlg.FileName.LastIndexOf('\\'));
    
        string filePath = Path.Combine(path, fileName);
    
        // This is "just-in-case" - say they created a new directory in the dialog,
        // but the dialog doesn't seem to think it exists because it didn't see it on-launch?
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
    
        // Remove a file if it has the same name
        if (File.Exist(filePath))
            File.Delete(filePath);
    
        // Write the file, assuming you have and pass in the bytes
        using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write)
        {
            fs.Write(bytes, 0, (int)bytes.Length);
            fs.Close();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 11:07

    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.

    //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;
    
    0 讨论(0)
提交回复
热议问题