This tutorial will show you one way of saving a text file from a Rich Text Box in a Windows Form. C# version.

Dealing with files in Visual Studio can be quite tricky. There are a number of ways to handle files, be it text or binary. There are a number of ways to open a file, create a file and edit a file.
In this tutorial, you will learn one way of saving text to a txt file. We will be using a Rich Text Box to input text, and then use a Menu Item to save to a txt file.

To begin, we will add a Menu Strip control to the form, and add a File > Save menu item (Just click to add), then we will also add a RichTextBox control. That’s all we need. The Windows Form Designer generated code will look something like this:

This is the code that is generated by Visual Studio when we design our form. Yours may look different.

Once we have added our controls to the form, we can start work on the code-behind.

To add an event handler to the menu item, simply double-click it like you would a button. We will add teh following logic:

In the above code, we are assigning a filename ourselves. This is not practical, and we will change this shortly. The code creates a new file with the StreamWriter, and then inputs the contents of our RichTextBox. We can improve this code by letting the user choose their own filename. We can use an Input Box borrowed from Visual Basic to do this. First, right-click the References folder of your Project in Solution Explorer, then choose Add Reference. Scroll down to Microsoft.VisualBasic and add that. Once done, we can change our code to the following:

This is much more practical, as it lets the user choose their own filename to save, which avoids overwriting. We still have problems, though. If Cancel is clicked on the InputBox, there is no filename for FileInfo to use, so it errors out. This isn’t good, so we can use an IF statement and also TRY and CATCH for any other errors:

This code is much more efficient, as it will catch any errors and notify the user. We also included the IF statement to let the user know that a filename is required.
The entire code-behind looks like this:

Download Source Files