Text file processing using C#

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 2884 red flag

This article is to show how to process text file using StreamReader and StreamWriter class

Text file processing using C#

In this article I am going to show how to process text file in C#.  In c# two popular classes are

1)StreamReader

                2)StreamWriter

there for file processing.  You have to import Sysyem.IO namespace to use those classes in your application. In this article we will see few examples of text file processing. Let’s start with object creation of those classes.

Create object of StreamReader and StreamWriter class

As those are nothing but class residing in System.IO namespace, the object creation mechanism is similar with normal class.

StreamWriter sw = new StreamWriter("D:\\text.txt");
StreamReader rd = new StreamReader("D:\\text.txt");

Here sw and rd are object of StreamWriter and StreamReader class simultaneously. 

StreamWriter class

Let’s see few examples with StreamWriter class in C# code. As the name suggest it’s use to write something in text file. In below code we are creating object of StreamWriter class by passing two arguments

StreamWriter sw = new StreamWriter("D:\\text.txt",true);

First argument is the location of text file. Means where is will create in our secondary device. And send parameter (true) is for append mode, if file already exists. If you want to create new file then make it false.

In below example I will show how to write single line to text file using StreamWriter object.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter("D:\\text.txt");
            sw.Write("Hello");
            Console.ReadLine();
        }
    }
}
 

This code will create one text file in my D drive. And the file will contain “Hello”.

Here we are using Write() function of StreamWriter class to write something on text file. We can use WriteLine(“String is here”) also for same purpose.

Now it’s always recommend to create StreamWriter(StreamReader also) object within using block. Like below.

using (StreamWriter sw = new StreamWriter("D:\\text.txt"))
            {
                sw.Write("Hello");
            }

To ensure that there will be proper implementation of garbage collection. In next few example will use using block always.  Now if you don’t want to implement using block then you can call Dispose method to release all resource allocated for StreamWriter class like below

 StreamWriter sw = new StreamWriter(@"D:\text.txt")
Sw.Dispose();
 StreamReader class

 By seeing name we can predict that this class is somehow related with reading data from text file.  Yes , We can use this class for the same. Let’s create object of StreamReader class like below.

StreamReader rd = new StreamReader(@"D:\text.txt")

The argument is nothing but path of text file. Once the object is created ,we can call various function associated with object to read text file. In below I have given few example.

Read() function

If you use Read() function of stream object it will show ASCII value of first character of text file. In below I have given sample code.

        static void Main(string[] args)
        {
            using (StreamReader rd = new StreamReader(@"D:\text.txt"))
            {
                Console.Write(rd.Read());
             }
            Console.ReadLine();
        }
 

ReadLine() function

This function will show first line of text file .Yes only first line.

        static void Main(string[] args)
        {
            using (StreamReader rd = new StreamReader(@"D:\text.txt"))
            {
                Console.Write(rd.ReadLine());
            }
            Console.ReadLine();
        }

 ReadToEnd()

By seeing name we can predict that , This function will fetch whole text file value. Below is the sample code to fetch whole value of text file.

static void Main(string[] args)
        {
            using (StreamReader rd = new StreamReader(@"D:\text.txt"))
            {
                Console.Write(rd.ReadToEnd());
            }
            Console.ReadLine();
        }

ReadBlock()

If we don’t want to fetch whole line or file content then we can use this function to read certain block from text file. ReadBlock() function takes three argument

First -> Character array for buffering purpose

Second-> Index from where it will start buffering

Third-> How many character it will take

Implementation of ReadBlock is in below.

 

        static void Main(string[] args)
        {
            using (StreamReader rd = new StreamReader(@"D:\text.txt"))
            {
                char [] val= new char[10];
                rd.ReadBlock(val,1,5);
            }
            Console.ReadLine();
        }

 Hope this article would be useful. Do write your comments.

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)