8

I want to open a save file dialog, have the user enter a filename, and if they forget the .csv extension, have it tacked on.

It would seem that the SaveFileDialog AddExtension property would work, but its doesn't. I've even set the DefaultExt property to .csv, and still nothing gets tacked on. My file gets saved just fine, but sans extension, so the user can't just double click on the file and have it open in Excel.

I have to be missing something obvious. Here's what I've got

        SaveFileDialog sfd = new SaveFileDialog();
        sfd.DefaultExt = "*.csv";
        sfd.Filter = "Comma Separated(*.csv)|*.*";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            // Do my file saving
        }
Jonathan Beerhalter
  • 7,229
  • 16
  • 68
  • 78

2 Answers2

13

Try just using "csv" for the DefaultExt - also, you should be using this (it is IDisposable):

        using (SaveFileDialog sfd = new SaveFileDialog())
        {
            sfd.AddExtension = true;
            sfd.DefaultExt = "csv";
            sfd.Filter = "Comma Separated(*.csv)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                // Do my file saving
            }
        }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

It doesn't tack on the extension in the dialog box, although it should. Instead, it tacks on the extension to sfd.filename when the dialog closes.