Share via


How to: Save a File to a Folder

You can use the built-in SaveFileDialog component to enable users to save a file to a folder. To display a dialog box, you use the ShowDialog method. You can then check whether the user clicked the OK button by using the DialogResult.OK field.

To display the folder browser dialog box

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. Click Windows Forms Application and then click OK.

  3. Add a RichTextBox control to the form, leaving the default name, RichTextBox1.

  4. Add a Button control to the form, and change the following properties in the Properties window:

    Property

    Value

    Name

    saveTextFile

    Text

    Save As

  5. Add a SaveFileDialog component to the form.

    saveFileDialog1 appears in the component tray.

  6. Double-click the button to add the default event handler in the Code Editor.

  7. In the saveTextFile_Click event handler, add the following code to display the Save As dialog box. This code saves the text typed in the RichTextBox control to a text file at the specified location.

    saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
    
    if(saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK
        && saveFileDialog1.FileName.Length > 0) 
    {
    
        richTextBox1.SaveFile(saveFileDialog1.FileName, 
            RichTextBoxStreamType.PlainText);
    }
    
  8. Press F5 to run the code.

  9. When the form appears, type some text in the rich text box.

  10. Click Save As and then browse to a folder where you want to save the text file.

  11. Specify a name for the text file, and then click OK.

  12. Verify that the text file exists at the specified location.

  13. Close the application.

See Also

Concepts

Using Built-in Dialog Boxes in Your Application

Designing a User Interface in Visual C#

Other Resources

Dialog Boxes (Visual C#)

Visual C# Guided Tour