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
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();
}
}