In this code snippet, we will see how to write and read files in C#.
In this example, I will use a console application. If you want to know how to open a file dialog and select/create a file in a WFA application see this post.
First, we will create a file(if it doesn’t already exist) using FileStream. Then we will write some text to the file using the StreamWriter class. Then we’ll use the StreamReader class to read from the file. All these operations need to performed inside a try catch block to prevent the application from crashing if an exception occurs.
Note: You don’t necessarily have to do exactly what was done here to read or write files. Instead of creating a file with FilesStream you could just pass its instance to StreamWriter. You can use the using keywod to simplify your code and avoid using the try catch block …
Let’s have a look at the code below to see how to read and write files.