How to save files using SaveFileDialog in C#

By FoxLearn 11/19/2024 2:19:45 PM   7.13K
To save the contents of a RichTextBox using a SaveFileDialog in C#, you can follow these steps.

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SaveFile" and then click OK

Drag and drop the RichTextBox, Button controls from Visual Toolbox onto your form designer, then design your form as below.

savefiledialog in c#

Add a SaveFileDialog, OpenFileDialog controls to your form, then add "Rich Text Format|*.rtf" to Filter property of SaveFileDialog, OpenFileDialog.

To handle the button click event in C#, you need to add an event handler method for the button’s Click event.

private void btnOpen_Click(object sender, EventArgs e)
{
    // c# read rtf file
    if (openFileDialog.ShowDialog() == DialogResult.OK)
        richTextBox.LoadFile(openFileDialog.FileName);
}

private void btnSave_Click(object sender, EventArgs e)
{
    // c# save the content of the RichTextBox to file
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
        richTextBox.SaveFile(saveFileDialog.FileName);
}

Use the RichTextBox.SaveFile method to save the contents to the selected file.

The SaveFileDialog allows the user to select a file location and specify the file name for saving.

The OpenFileDialog in C# is used to display a dialog that allows the user to select a file from the file system to open.

The Filter property defines the types of files that can be saved (e.g., RTF or TXT files).

VIDEO TUTORIAL