Displaying the Save As Common Dialog Box

The Save As dialog box enables a user to browse through directories and select a file name or enter a new file name. Similar to the Open dialog box, the Save As dialog box has properties that enable you to change the appearance and behavior of the dialog box. For example, you can define filters for file names or display a message to a user if a file name already exists.

The Save As dialog box uses the FileName, FileTitle, DefaultExt, and InitDir properties to provide a default path, file name, and extension. You can set the caption for the dialog box with the DialogTitle property and set filters that display only certain files with the Filter and FilterIndex properties. The Flags property enables you to control other dialog box behaviors.

Use the ShowSave method to show the dialog box after you set its properties. When the ShowSave method returns, the application can read the properties of the control to determine the choices a user made in the dialog box.

The following code example shows how to display a Save As common dialog box and return the selected file name and path.

Public Function GetFileToSave()
    Dim fileflags As FileOpenConstants
    Dim filefilter As String
    'Set the text in the dialog title bar
    CommonDialog1.DialogTitle = "Save As"
    'Set the default file name and filter
    CommonDialog1.DefaultExt = "txt"
    CommonDialog1.InitDir = "\"
    CommonDialog1.FileName = ""
    filefilter = "Visual Basic Files (*.vb)|*.vb|All Files (*.*)|*.*"
    CommonDialog1.Filter = filefilter
    CommonDialog1.FilterIndex = 0
    'Prompt to create the file if it does not exist
    'and prompt to overwrite if the file exists
    fileflags = cdlOFNCreatePrompt + cdlOFNOverwritePrompt
    CommonDialog1.Flags = fileflags
    'Show the Save As common dialog box
    CommonDialog1.ShowSave
    'Return the path and file name selected or
    'Return an empty string if the user cancels the dialog
    GetFileToSave = CommonDialog1.FileName
End Function