Ed Marty
Ed Marty

Reputation: 39690

Change file extension when user changes Save As Type in SaveFileDialog

I have a SaveFileDialog with the option of saving with type .foo or .bar. The first item in the list, and selected by default, is .foo. The default filename is "untitled", and the default extension is ".foo". When the SaveFileDialog appears, it puts "untitled" in the file name textbox. I can change it to "untitled.foo" but it still doesn't change the behavior in regards to my problem:

If the user switches to .bar, how can I make the filename change to untitled.bar? There's only two events, neither of which is the one I want, and it doesn't seem to be changing itself.

Upvotes: 8

Views: 23286

Answers (5)

Chocolate Soong
Chocolate Soong

Reputation: 1

//Drag a SaveFileDialog from toolbox, and then...
//Create a button.... let's say this is my button named button1
private void button1_Click(object sender, EventArgs e)
{
  //saveFileDialog1 is the tool you grabbed from toolbox and could be renamed if you want
  //using Filter.. so user will see the extension has been selected by default
  saveFileDialog1.Filter = "Text Document(.txt)|.txt";
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
    /*saveFileDialog1.Filter = "Text Document(.txt)|.txt";*/
    File.Create(saveFileDialog1.FileName);
    MessageBox.Show("New file created succesfully!");
  } else {
    MessageBox.Show("Unsuccessful!");
  }
}

Upvotes: 0

Ahmed Suror
Ahmed Suror

Reputation: 500

You may do: savefiledialog1.AddExtension = True

Upvotes: 0

MEF2A
MEF2A

Reputation: 238

Adding DefaultExt and AddExtension will give you the behaviour you're looking for. Simialr to question/answer provided here: https://stackoverflow.com/a/1213353/101971

        var saveFileDialog = new SaveFileDialog
                                 {
                                     Filter = "Foo (*.foo)|*.foo|Bar (*.bar)|*.bar",
                                     DefaultExt = "foo",
                                     AddExtension = true
                                 };

Upvotes: 2

BeemerGuy
BeemerGuy

Reputation: 8269

Ed,
I just tested and it works just fine.
I did this:

        SaveFileDialog sfd = new SaveFileDialog();

        sfd.FileName = "untitled";
        sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
        sfd.ShowDialog();

And it automatically changes the suggested save name depending on the filter I choose.
I used the .NET 2.0 framework.
But I'm on Windows 7, which I think matters, since you see the system's file-save dialog, and the way it's implemented is what matters here.

Upvotes: 11

CodeMonkey1313
CodeMonkey1313

Reputation: 16011

When you go to actually save the file you can get the file name from the dialog box, then perform the necessary string manipulation from there. The file name is a member of the instance of the SaveFileDialog

Upvotes: 1

Related Questions