C# Reading and Writing Files

C# Code Snippets Reading and Writing Files
Share:

About

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.  

Code:

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger