C#: Save File Dialog

person Jason Huangfolder_open.NET, C#, Codelocal_offer, , , access_time September 18, 2009

It’s fairly easy to call up the standard windows File Save dialog box.

The following simple example shows you how to create an instance of SaveFileDialog, then assign different properties.
Some of the properties:

  • Title : name of the Save Dialog Box (such as “Save this text file to your document”)
  • InitialDirectory: when the dialog box opens, this is the directory/folder it opens at. If you want it to be in C:\, set it to “C:\”
  • Filter: Filter of file name (extension)
  • FilterIndex: if you have multiple filter defined, you can set which is by default is the one be used initially.
  • FileName: you can set a default filename when Save File Dialog opens, the user would be able to overwrite it.

After all the properties are set, you can invoke / open the Save File Dialog by calling the method ShowDialog().


SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Title = "Add log files to zip?";
//saveFileDialog1.InitialDirectory = sOutputFolder;
saveFileDialog1.Filter = "ZIP files (*.zip)|*.zip"  ;
saveFileDialog1.FilterIndex = 0 ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.FileName = System.DateTime.Today.Month + "-" + System.DateTime.Today.Day + "-" + System.DateTime.Today.Year + ".zip";
 
//use a if here to see if the user actually click save button.
//if DialogResult.OK means the user actually click save button.
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
   //do something here using the filename
  string filename = saveFileDialog1.FileName;
}

Comment

  1. Przemek Sech

    More elegant is:
    saveFileDialog1.FileName = “Harm_” + DateTime.Now.ToString( “yyyy-MM-dd-HH-mm-ss” );

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>