File Reading and Writing in C#

During program execution, data is saved and loaded from the main memory of the computer. Once program is closed, all the data is erased from the memory. What if you want your data to persist somewhere on your computer for future use? Suppose you have a point of sale system where you want to save your customers bio data. How would you do that?

You need a mechanism to read or write data to the file so that you can retrieve it in future. Usually a database is used for highly level related data storage. However, simple and plain data can also be stored in ordinary files. This article explains how you can read and write data to a text file.

Reading Data from Text File

Before executing the code, create a text file named “docs.txt” and add following text in it:

Crazy brown fox
Jumps over the lazy dog
and this is crazy..

Save the file, in the root of your “D:” directory and execute following code.

´╗┐using System;
using System.IO;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            try {
                // Creating object of stream reader class
                using (StreamReader textreader = new StreamReader("d:/docs.txt")) {
                    string text;
                    // ReadLine function is used to read all lines in the text
                    while ((text = textreader.ReadLine()) != null)   {
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e) {
                // Display message if some issue occurs
                Console.WriteLine("Problem reading the file.");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, StreamReader class is being used to read the file. The path of the file to be read is passed to the constructor of the StreamReader class. The ReadLine method of the StreamReader class reads one line of text at a time and if text exists on the next line, it returns true.

Writing Text to a File

Writing text to the file is done via StreamWriter class. The WriteLine method of the class is used to write text, line by line to a text file. Have a look at the following example.

´╗┐using System;
using System.IO;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] statements = new string[] { "Hi, crazy wolf", "I know it makes no sense", "Still its cool." };
            using (StreamWriter textwriter = new StreamWriter("D:/sometext.txt")) {

                foreach (string statement in statements) {
                    textwriter.WriteLine(statement);
                }
            }

            // Reading the text which is written
            string text = "";
            using (StreamReader filereader = new StreamReader("D:/sometext.txt"))  {
                while ((text = filereader.ReadLine()) != null)  {
                    Console.WriteLine(text);
                }
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above program some random lines of text have been written to sometext.txt file which will be created at the root of the D: directory. Then again,the file that has been written is read via StreamReader object.

<<< Dictionaries in C#Introduction to LINQ >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .