Topic : File Handling » Sequential Access File in C# Programming Language:



Sequential Access File:

A Sequential file has to be Accessed in the same order the file was written. Let's take an example of Cassette Tapes: We play music in the same order it was recorded. we can Quickly fast-forward or rewind over songs we don't want to listen to, but the order of the songs dictates what we do to play the song we want. But it is difficult, and sometimes impossible, to insert data in the middle of two other songs on a tape. The Only way to truly add or delete records from the middle of a Sequential file is to create a completely New file that combines both old and new records. With Sequential files, We can Do following Operation in C#:




image: Sequential File Handling

Opening & Closing Files:

In C#, The process of Opening and Closing or Manipulating files requires a lot of Language background to prepare us for the complexity of the Operation. However The C# Namespace System.IO Provide us a simple way to Manipulate files, so in just a single steps we can Open or close any file.

A file must be Opened before reading or writing Operation. To Open a File or Create a New File, We need to Create a FileStream. Let's have an Example to know how we can Open or Close The File:



/*Example - File Handling: Opening & closing file  - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            //Open or Create new file, and Named "info.txt":
            FileStream MyFile = new FileStream("info.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            /*
             Perform some Operation on file:
             */

            //close the file:
            MyFile.Close();

        }
    }
}


In Above Example, We Open a file using the FileStream Object File. This object will Open the File named info.txt for reading and writing purpose. if the file doesn't exist, it will create a new file. The FileStream Object new Three Parameters, in our previous tutorial, we discuss it already. We will perform some operation and at the end, we will close the file using close() Method.

While Opening the File, there could be a problem. Like there is no space available, or the file name is not valid. there are many cases to create an error while opening the file. So Its really good Programming practice to Include some error checker in our Program. This error checker will help us to reduce the chance of error in our Program. so let's see how we can write an error checker in our code.


/*Example - File Handling: Error Checker - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            //Check if the file exist:
            string FilePath = @"D:\Info.txt";  //file name:
            if(File.Exists(FilePath))  
            {
                Console.WriteLine("File Exist: ");
            }
            else
            {
                Console.WriteLine("File not exist: ");
            }
            
            Console.ReadKey();

        }
    }
}

In Above example, we just include an error checker code. this code will check whether the file is exist or not. we use an method Exists(), this method specified whether the file exist or not.



Reading & Writing Operation:

After Opening the files, we can read from files and write to file using StreamReader and StreamWriter Classes respectively. These classes inherit from the Abstract base class stream, which supports reading and Writing bytes into a File Stream.



StreamWriter Class - Writing to Files:

The StreamWriter Class inherits from the Abstract class TextWriter that represent a writer, Which can write a series of Character. It is very easy to write data into a text file using StreamWriter Class and most of the beginners prefer to use this class in writing file. The Following tables show some of the most used method of this Class:



MethodDescription:
Close()Closes the current StreamWriter object and the underlying stream.
Flush()Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Write()This method is used to write data to a text stream without a newline.
WriteLine()This method is used to write data to a text stream with a newline.


Let's have an Example where we will know, how we can write a data into a File using StreamWriter Class:


/*Example - File Handling: StreamWriter Class - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            string message;
            string MyFile = @"D:\info.txt";  //file name:

            Console.WriteLine("Enter Your Message to Store: ");
            Console.Write("Message: "); //enter your message:
            message = Console.ReadLine();

            //Open the file for Writing purpose.
            using (StreamWriter write = new StreamWriter(MyFile))
            {
                write.Write(message); //write the msg into file named "info.txt".
            }

            Console.WriteLine("Message Store Successfully: \n\n");

            Console.ReadKey();
        }
    }
}


In Above example, the program get the string from user and store it in the file named "Info.txt" located in drive D. Go to your Drive D and you'll find the file there with same text that you write in the Console application.



StreamReader Class - Reading from Files:

The StreamReader Class inherits from the Abstract base Class TextReader that represents a reader for reading series of Characters. Its implementation is easy and it is widely popular among the programmer. However, there are dozens of way to read text file in C# file handling but StreamReader Class is more popular in list. The Following table describes some of the commonly used Methods of the StreamReader Class:



MethodsDescription
Close()It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
Peek()Returns the next available character but does not consume it.
Read()Reads the next character from the input stream and advances the character position by one.


Let's Have an Example, where we will try to read the same text file "info.txt" using the StreamReader Class.



/*Example - File Handling: StreamReader Class - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyFile = @"D:\info.txt";  //file name:

            try
            {
                //Open the file for Reading Purpose:
                using (StreamReader sr = new StreamReader(MyFile))
                {
                    string line;
                    /*Read and display lines from the file until 
                     reach at the end of the file:*/
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }

                }
            }

            catch (Exception e)
            {
                //Error Checker.
                //Catch the exception, 
                Console.WriteLine("Error While Opening the File " + MyFile);
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
    }
}


In Above example, we Create an instance of StreamReader to read the file. We read the file using while Loop. this loop start to reading the file from start upto the end of the file. we include error checker in our code. if any error occur, the program will throw the exception and user can see, what the error is. just try to change the file Name, and compile it again, and check what is displays.



Deleting The file:

We can use Delete() Method to delete any file permanently. let's have an example, where we will try to delete the file that we create and read in our previous example.



/*Example - File Handling: Deleting the File - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyFile = @"D:\info.txt";  //file name:
            File.Delete(MyFile);   //delete the file named "Info.txt".


            try
            {
                //Opne the file for Reading Purpose:
                using (StreamReader sr = new StreamReader(MyFile))
                {
                    string line;
                    /*Read and display lines from the file until 
                     reach at the end of the file:*/
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }

                }
            }

            catch (Exception e)
            {
                //Error Checker.
                //Catch the exception, 
                Console.WriteLine("Error While Opening the File " + MyFile);
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
    }
}


In our Example, we use same example, that we write to read and write the file. but in this example, before reading the file, we delete the file and then try to read it. but we Error checker code find out that the file doesn't exist. because we already delete it.



TextWriter & TextReader:

We can use TextWriter and TextReader Class for Writing and Reading Purpose Respectively.


  • » The TextWriter Class Represents a Writer that can write Sequential Series of Characters. We can use this class to Write text in a file. it is an Abstract base Class of StreamWriter Class, Which write Characters to stream.
    » The TextReader Class Represent a Reader that can read a Sequential Series of Characters. We can use this class to read text from the file. It is an Abstract Base class of StreamReader Class, which read Characters from the Stream.


Let's have an simple and short example to know, how we can use these class to read or write from the file.


/*Example - File Handling: TextWriter & TextReader - InfoBrother*/

using System;
using System.IO;

namespace FileHandling
{
    class Program
    {
        static void Main(string[] args)
        {

            //TextWrite class to write the text into the file:
            //Open the file for writing purpose:
            TextWriter tw = new StreamWriter("file.txt");
            tw.WriteLine("Hello and Welcome to C# Tutorials: ");
            tw.Close();   //close the file:


            //TextReader Class to read the Text from the file.
            //Open the File for reading purpose:
            TextReader tr = new StreamReader("file.txt");
            Console.WriteLine(tr.ReadLine());
            tr.Close();   //Close the File:

             Console.ReadKey();
        }
    }
}


















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement