Red Write Text File In C#

This step-by-step article explains how a text file can be read and written using Visual C#.

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you must have:

  • Visual C#


This article assumes that you are familiar with the following topic:

  • Visual C#

 

Read Text File

Read a Text file section of this article, defines how to read a text file with the StreamReader class. The following code is used to open, read and close a text file by the StreamReader class. The text file path can be passed to StreamReader constructor to automatically open the file. Each line of text is read by ReadLine and the file-pointer is increased to the next row. When the method Readline reaches the end of the file, a null reference is returned.

 

 

1. In Notepad, create a sample text file. Follow these measures to do this. In Notepad, add the following text.

  • Hello Uttarakhand!
  • Save the file as Sample.txt.

 

2. Start Microsoft Visual Studio

3. On the File menu, point to New, and then click Project.

4. Click Visual C# Projects under Project Types, and then click Console Application under Templates

5. At the start of Class1.cs, add the following code:


using System.IO;

Note: In Visual Studio 2005 or Visual Studio 2008, the default file is Program.cs

6. In the main method, add the following code.


using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        String line;
        try
        {
            //Pass the file path and file name to the StreamReader constructor
            StreamReader sr = new StreamReader("C:\\Sample.txt");

            //Read the first line of text
            line = sr.ReadLine();

            //Continue to read until you reach end of file
            while (line != null)
            {
                //write the lie to console window
                Console.WriteLine(line);
                //Read the next line
                line = sr.ReadLine();
            }

            //close the file
            sr.Close();
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}

7. On the Debug menu, click Start to compile and to run the application. Close the console window by pressing ENTER. The Console window shows the Sample.txt file contents.

Output:

Hello Uttarakhand!

Write a Text File

Write a Text file section, describe how to write text to a file by using the StreamWriter class. The following code is used to open, write, and close the text file by StreamWriter class. Similar to the StreamReader class, we can pass a text file path to the StreamWriter constructor to automatically open this file. The WriteLine method writes a full text line in the text file.

 

 

1. Start Visual Studio

2. On the File menu, point to New, and then click Project.

3. Click Visual C# Projects under Project Types, and then click Console Application under Templates.

Note: In Visual Studio 2005 or Visual Studio 2008, click Visual C# under Project Types, and then click CLR Console Application under Templates.

4. At the start of the class1.cs file, add the following code.


using System;
using System.IO;

Note: In Visual Studio 2005 or Visual Studio 2008, the default file is Program.cs

5. In the main method, add the following code.


        try
        {

            //Pass the filepath and filename to the StreamWriter Constructor
            StreamWriter sw = new StreamWriter("D:\\Test.txt");

            //Write a line of text
            sw.WriteLine("Hello Uttarakhand!!");

            //Write a second line of text
            sw.WriteLine("From the StreamWriter class");

            //Close the file
            sw.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }

Click Start to compile and execute the application in the debug menu. This code generates a file on drive C called Test.txt. In a text editor such as Notepad, open Test.txt. Test.txt has two text lines:

Hello Uttarakhand!!
From the StreamWriter class

 

We can open, write and close the text files using the StreamWriter class. This code passes two additional parameters to the constructor, unlike in the previous example. The first parameter is the file path and the file name of the file. The second parameter, True, sets the file in append mode. If the second parameter is specified by False, each time we run the code, the file's contents are overwritten. Unicode is specified by the third parameter, so StreamWriter encodes the Unicode file.

The following encoding method for the third parameter can also be specified:

  • ASC11
  • Unicode
  • UTF7
  • utf8mb4

 

The Write method is similar to the WriteLine method, unless the Write method automatically doesn't embed a combination of carriage return or flight feed (CR / LF). This is helpful if one character should be written at a moment.

 

 

1. Start Visual Studio.

2. On the File menu, point to New, and then click Project.

3. Click Visual C# Projects under Project Types, and then click Console Application under Templates

4. At the start of the Class1.cs file, add the following code:


using System.IO;
using System.Text;

Note: In Visual Studio 2005 or Visual Studio 2008, the default file is Program.cs

5. In the main method add the following code.


        Int64 x;
        try
        {
            //Open the File
            StreamWriter sw = new StreamWriter("D:\\Test1.txt", true, Encoding.ASCII);

            //Writeout the numbers 1 to 10 on the same line.
            for (x = 0; x < 10; x++)
            {
                sw.Write(x);
            }

            //close the file
            sw.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }

To compile and run the application, press Start in the Debug menu. This code generates a file on drive C called Test1.txt. Open a text editor like Notepad for Test1.txt. Test1.txt includes a single text line:

Output:

0123456789

 

 

Read a Text File, Write a Text File (Example 1) and Write a Text File(Example 2)



//Read a Text File
using System;
using System.IO;

namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {

            String line;

            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Sample.txt");

                //Read the first line of text
                line = sr.ReadLine();

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the lie to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }

                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}


//Write a text file - Example-1
using System;
using System.IO;

namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            try
            {

                //Pass the filepath and filename to the StreamWriter Constructor
                StreamWriter sw = new StreamWriter("C:\\Test.txt");

                //Write a line of text
                sw.WriteLine("Hello Uttarakhand!!");

                //Write a second line of text
                sw.WriteLine("From the StreamWriter class");

                //Close the file
                sw.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}



//Write a text file  - Example 2
using System;
using System.IO;
using System.Text;

namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {

            Int64 x;

            try
            {
                //Open the File
                StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);

                //Writeout the numbers 1 to 10 on the same line.
                for (x = 0; x < 10; x++)
                {
                    sw.Write(x);
                }

                //close the file
                sw.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

It is good programming practice to put the code into an try-catch block to handles errors and exceptions for all file manipulations. Specifically in the final block, we may want to release handles to the file, so the file will not be locked permanently. A file that doesn't exist or file that is already in use are some possible errors.

See the Microsoft Developer Network (MSDN) Web portal for more information:

StreamReader Class
http://msdn2.microsoft.com/en-us/library/system.io.streamreader(vs.71).aspx

 

Download Read Write Text File Source Code in C#