File read and write in C#



You are often required to read data or content from a file. For example, you may be willing to read a CSV file and the plot a chart based upon its content. Or you may like to format the data in the file and then write it back to the file. In this tutorial we will see how to read and write to file.
We will start with the file write as it is easiest things to start with. The whole focus on the referencedesigner.com tutorial is to start with "something easier". So here is the code written and run in Visual. C# Express We make use of the System.IO namespace, that contains types that allow reading and writing to files and data streams. You can get more details about it at Microsoft's website here . For the moment we will write a simple program that just creates a file and write a line in it. Take a look at the following code.

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

// The above is required for file IO

// We are trying to learn how to create and write to a file 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new file to write

            TextWriter nf = new StreamWriter(@"C:\tutorials\test.txt");
            // The new file is created in the directory C"\tutorials
            nf.WriteLine("It is easy to learn with referencedesigner.com tutorials");
            // now close the file
            nf.Close();
            
        }
    }
}


  

Here is the youtube that explains the complete process.

Some Explanation

The line

 TextWriter nf = new StreamWriter(@"C:\tutorials\test.txt");


Initializes a new instance of the StreamWriter class for the file C:\tutorials\test.txt using default encoding and buffer size. You can read more abot the StreamWriter at it here

Reading a File

To read a file we make use of the TextReader class. Take a look a the following example. The contents of the file input.txt is as follows

Referencedesigner.com C# Tutorial
This is second line
This is third line




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

// The above is required for file IO

// We are trying to learn how to create and write to a file 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new file to write

            TextReader nf = new StreamReader(@"C:\tutorials\input.txt");
            // The new file will be read from the file  C:\tutorials\input.txt
            Console.WriteLine("This is line 1 "+nf.ReadLine());
            Console.WriteLine("This is line 2 " + nf.ReadLine());
            Console.ReadLine();
            // now close the file
            nf.Close();
            
        }
    }
}

   
  


If you run this code, you get the output as follows
Here is the youtube tutorial, showing the complete process