Saving Data to a Text File
This guide will show you how to use StreamWriter and StreamReader to save and retrieve data.

Step 1: Add the required library
Add the top of the form type the code:
using System.IO;

Step 2: Save Data
Choose when you want the data to be saved e.g. when the user clicks the SAVE button. Add the following code to save the word hello into a file called myFile.txt. If the file does not exist, it will be created.
using (StreamWriter s = new StreamWriter("myFile.txt"))
{
s.Write("hello");
}
The file will be saved into your project file inside the bin/Debug/net${dotnet-version} folder. You will be able to open it in Notepad and check the contents.
Note:
Write() will save each word next to the last.


WriteLine() will save each word on a seperate line.
using (StreamWriter s = new StreamWriter("myFile.txt"))
{
s.WriteLine("hello");
s.WriteLine("how");
s.WriteLine("are");
s.WriteLine("you?");
}
Step 3: Retrieve Data
Method 1: Retrieve all data together.
Use StreamReader to retrieve the data from the file myFile.txt. The following will assign all of the file data to the String variable s.


Method 2: Retrieve data line by line.
The following code will retrieve each line of data from the file and store in the String variable s. It will then display the data.


Advanced - CSV Files
You may want to organise your data into columns, Click here to find out more about saving data into CSV Files.