When you run your C# application, your OS loads application code as well as application related data into system memory and executes operations defined by your application code. The application data remains in the memory of the system as long as your application is running. As soon as you close your application, your application data is wiped out of your memory.
For instance, you might have developed some software that records daily attendance of students in some school. You open the software tick the check boxes against student names and close the software. What happens? If you are not saving student attendance to some file, attendance records are lost. Since, when you close the software, everything in the computer memory, including variables which store attendance, will be wiped out of the memory.
This situation is where file handling comes into play. File handling refers to the process of reading and writing data to some file. The file can be of any form, ranging from a simple text file containing some string to advanced database files. In almost all of the cases, you would use database files for storing your application data. Database management allows easy manipulation of database files. However, in some cases, you might also consider using files for data storage and retrieval. In this article, I will explain what the different ways are of working with files in C#. Now enough of theory, let’s get to real coding stuff!
StreamReader and StreamWriter Classes
In C#, many classes can be used for interacting with files in C#. For reading and writing text files the StreamReader and StreamWriter classes are most commonly used.
Reading a Text File
Let’s first see how to read text files via the StreamReader class. The path of the file to read is passed as a parameter to the constructor of the StreamReader class. Next, the ReadLine method is called inside a loop. The ReadLine method reads the text file line by line and returns one line during each iteration. Once all the lines in the document are read, the ReadLine method returns null. Take a look at the following example to see how StreamReader class can be used to read files. Suppose we have a file named “Sample.txt” with the following text:
Humpty Dumpty Sat on a Wall Humpty Dumpty Had a great Fall All the King's Horses and all the King's Men Could not put Humpty Dumpty together again
Take a look at the following C# code to see how you can read the text file.
using (StreamReader reader = new StreamReader("E:/Sample.txt")) { string text; while ((text = reader.ReadLine()) != null) { Console.WriteLine(text); } }
In the above code, you can see that StreamReader object “reader” is being created inside the using block. This is to make sure that as soon as the using block ends, the “reader” object is flushed out of the memory. Another important thing to note here is that you need to include “System.IO” namespace to use StreamReader and StreamWriter classes.
Now, coming back to the code, if you run the above code, you shall see the text of the “Sample.txt” file displayed in the output.
Writing to a Text File
Writing text to a file is as simple as reading it from a file. The path to the text file where you want to write content is passed as a parameter to the constructor of the StreamWriter class. Next, the WriteLine method is called to write a line of text to the file. The line of text you want to write in the file is passed as a parameter to WriteLine method. Each time you call WriteLine method, a new line of text is appended to the document. Take a look at the following example to see how this works.
string[] countries = new string[] { "USA", "England", "Germany" }; using (StreamWriter writer = new StreamWriter("E:/Sample2.txt")) { foreach (string item in countries) { writer.WriteLine(item); } }
Execute the above code and go to the root of your “E:/” directory. You will see a file named “Sample2.txt”. Open the file and you will see names of three countries on three separate lines.
What happens is, while writing text via StreamWriter class, if the file doesn’t exist at the specified path, the StreamWriter class first creates the file.
Using File Class to Read All Text
The StreamReader class reads file contents line by line. However, if you are interested in reading all the text inside a file at once, you should use static File class. The “ReadAllText” method of the File class is used to read all the text inside a document and return it in the form of a formatted string. We will again read “Sample.txt” class which contains the Humpty Dumpty rhyme. Take a look at the following code snippet.
string filereader = File.ReadAllText("E:/Sample.txt"); Console.WriteLine(filereader);
Yes, that is just two lines of code. You simply have to pass the path to the file you want to read, as a parameter to the ReadAllText function and it will read all the text inside that file.
You can also read the contents of the file in the form of lines using ReadAllLines function of the File class. The ReadAllLines function returns string array where each line is stored as one item of the array. Take a look at the following example.
string[] filereader = File.ReadAllLines("E:/Sample.txt"); foreach (string item in filereader) { Console.WriteLine(item); }
Using File Class to Write All Text
StreamWriter class had WriteLine method which was used to write text to file one line at a time. You can write multiple lines of text all at once using WriteAllText and WriteAllLines method. The WriteAllText method only accepts a string as a parameter whereas WriteAllLines method accepts an array of strings. Take a look at the following example to see how WriteAllText and WriteAllLines method works.
string[] countries = new string[] { "USA", "England", "Germany" }; File.WriteAllText("E:/Sample3.txt", "China Japan Korea"); File.WriteAllLines("E:/Sample4.txt", countries);
Now, if you go to your “E:/” directory and open the “Sample3.txt” file, you should see “China Japan Korea” written in it. Similarly, in file “Sample4.txt” you will see “USA”, “England” and “Germany written” line by line since they are written via the WriteAllLines method.
This article explains some of the different ways of working with files in C#. We saw how the StreamWriter and StreamReader classes are used to write to and read from a file line by line. Finally, we covered how the static File class helps read all the data from the file and write all the data to the file at once. In the next article, we will take a look at arrays and lists in C#.
If you have any question about this article please leave a comment below or send me a message via my contact page.