mikeminer
mikeminer

Reputation: 197

WPF C# SaveFileDialog - Reopen Dialog if filename exists in alternate folder

I have a WPF project where I have a "Backup" folder that autosaves. If the user chooses a different name when they save the project, I check the Backup folder first and warn them if there's already a project with that name. If so, I want to reopen the SaveFileDialog and allow them to rename.

SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ".xml";
dlg.Filter = "xml documents (.xml)|*.xml|All Files (*.*)|*.*";
dlg.FileName = ProjectName;
bool? result = dlg.ShowDialog();

if (result == true)
{
    string changedFilename = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
    if (changedFilename != CurrentProjectName)
    {
        if (ExistingProjectNames.Contains(changedFilename))
        {
            if (MessageBox.Show("Project name " + changedFilename + " already exists. Continue?", "Existing Project Name", MessageBoxButton.OKCancel, MessageBoxImage.Warning) == MessageBoxResult.OK)
            {
                CurrentProjectName = changedFilename;
                WriteFile(dlg.FileName);
            }

            else
            {
            //go back to beginning and open dialog again so user can rename
            }

It seems pretty simple, but I can't think of the best way to do this. I've thought of recursion and switch statements, but it seems like I'm making it too complicated. Is there a more "standard" way to do this?

Upvotes: 0

Views: 313

Answers (1)

Xavier
Xavier

Reputation: 3404

One thing you can do is register for the FileOk event on the dialog before showing it. The event handler will be called when the user presses the Save button in the dialog, and you have the option of setting e.Cancel = true to prevent the dialog from closing and allow the user to make another choice.

Another option is to show the dialog in a while loop until whatever condition is satisfied, causing it to keep reopening until the user does what they need to do.

Upvotes: 1

Related Questions