Random Access File:
In This Tutorial, We are Introduction the concept of Random file Access. Unlike Sequential files, we can access Random Access files in any order we want. Think of data in a Random Access file as we would songs on a compact disc or record, we can go directly to any song we want without having to play or fast-forward over the other songs. If we want to play the first song, the sixth song, and then the fourth song, we can do so. The order of play has nothing to do with the order in which the songs were originally recorded. Random-file access sometimes takes more Programming but rewards our effort with a more flexible file-access method .
Random file access enables us to read or write any data in our disk file without having to read or write every piece of data before it. We can Quickly search for data, Modify data, delete data in a random-access file. We can open and close Random access file same like Sequential files with same opening and closing methods, but we need a few new Methods to access files randomly, we find that the extra effort pays off in flexibility, power, and speed of disk access:
The process of randomly accessing data in a file is simple. Think about the data files of a large credit card organization. When we make a purchase, the store calls the credit card company to receive authorization. Millions of names are in the credit card company’s
files. There is no quick way the credit card company could read
every record sequentially from the disk that comes before Ours.
Sequential files do not lend themselves to quick access. It is not
feasible, in many situations, to look up individual records in a data file with sequential access.
The credit card companies must use a random file access so their computers can go directly to our record, just as we go directly to a song on a compact disk or record album. The Methods we use are different from the sequential Methods, but the power that results from learning the added Methods is worth the effort.
When our program reads and writes files Randomly, it treats the file like an big Array. with Arrays, we know we can add, print, or remove values in any order. we don't have to start at the first array element, Sequentially looking at the Next one, Until we get the Element we need. We can view our Random-access-file in the same way, accessing the data in any order.
File-Pointer: File-pointer is an special type of pointer that is used to keep track of the current read/write position within the file. when something is read from the file or written to file, the reading/writing happens at the file pointer's current location. By default, when opening a file for reading or writing, the file pointer is set to the beginning of the file. However, if a file is opened in append mode, the file pointer is moved to the end of the file
For doing this all operation, we have just one Important things that we need to know about before Move on. The thing is file-pointer, this File-Pointer move sequentially but we can also make it to move Randomly using some Methods.
Read Data From AnyWhere Within The File:
In Random access file, we can read data from anywhere within the file. We just need to move our file Pointer from where we want to read the data. to move this pointer, C# provide us a simple method Seek() to play with file pointer. using this method we read data randomly. The basic syntax for this method is:
Seek( value SeekOrigin.Origin);
Let's have an example, where we will use Seek() method to read data randomely. Look at this short and simple example.
/*Example - File Handling: Read from Anywhere within The file - InfoBrother*/
using System;
using System.IO;
namespace FileHandling
{
class Program
{
static void Main(string[] args)
{
string filename = @"D:\data.txt"; //file name;
string name = "InfoBrother"; //Name
//Write Name into The File:
using (StreamWriter write = new StreamWriter(filename))
{
write.Write(name);
}
//read from file:
try
{
//Open the file for reading purpose:
using (FileStream read = new FileStream(filename, FileMode.Open))
{
Console.WriteLine("In Word " + name);
int first = read.ReadByte();
Console.WriteLine("The First Character is: \"{0}\" ", (char)first);
long length = read.Length;
//Move the File Ponter in the middle of the name:
read.Seek(length / 2, SeekOrigin.Begin);
int middle = read.ReadByte();
Console.WriteLine("The Middle Character is: \"{0}\" ", (char)middle);
//Move the file pointer before one character from the end:
read.Seek(-1, SeekOrigin.End);
int last = read.ReadByte();
Console.WriteLine("The Last Character is: \"{0}\" ", (char)last);
read.Close();
}
}
catch(IOException ex)
{
Console.WriteLine("Error occur while reading the File: ");
Console.WriteLine(ex);
}
Console.ReadKey();
}
}
}
Read Data From AnyWhere Within The File:
In Word InfoBrother
The First Character is: "I"
The Middle Character is: "r"
The Last Character is: "r"
We can Find and Modify our Record.
To Modify Our Record, We can use Replace() Method. This method is a great way to replace easily the parts of string or certain charaters of a String. To use this method, we need to pass two parameters through it, the first will be the character we want to replace, and the second will be what we need to replace with it. The parameters should be in Quotes and separated by comma. The basic syntax for using Replace() is:
Replace("Find What", "Replace with");
/*Example - Random Access file - Replace Method - InfoBrother*/
using System;
using System.IO;
namespace Modifying
{
class Program
{
static void Main(string[] args)
{
string message = "A Quick Fox Jumps Over The Dog:";
String FileName = @"D:\Greeting.txt";
//Open the file for writing purpose:
TextWriter tw = new StreamWriter(FileName);
tw.WriteLine(message);
tw.Close();
//Open the file for Reading purpose:
TextReader tr = new StreamReader(FileName);
Console.WriteLine("Before=> "+ tr.ReadLine());
tr.Close();
//Using Replace Method
string str = File.ReadAllText(FileName);
str = str.Replace("Fox", "Brown Fox");
str = str.Replace("Dog", "Lazzy Dog");
File.WriteAllText(FileName, str);
//Open the file for Reading purpose:
TextReader tr2 = new StreamReader(FileName);
Console.WriteLine("After => " + tr2.ReadLine());
tr2.Close();
Console.ReadKey();
}
}
}
Replace() Method | Modify record:
Before=> A Quick Fox Jumps Over The Dog:
After => A Quick Brown Fox Jumps Over The Lazzy Dog:
We can Delete specific record.
In order to remove some data from the file, we need to create another temporary file. we will read from old file, and will find out the data to be delete. then we write all data into the temporary file, skipping the data that we want to delete. check out the example below to clear your concept.
/*Example - Random Access file - Deleting Record - InfoBrother*/
using System;
using System.IO;
namespace Deleting
{
class Program
{
static void Main(string[] args)
{
String Old = @"D:\OldFile.txt"; //existing file:
String New = @"D:\NewFile.txt"; //New file:
string line = null;
//find this line and delete it:
string line_to_delete = "My Name is Omar";
//read all text from old file:
using (StreamReader sr = new StreamReader(Old))
{
string chr;
while((chr = sr.ReadLine()) != null)
{
Console.WriteLine("From Old File: => " +chr);
}
}
//Open old file for reading purpose
using (StreamReader reader = new StreamReader(Old))
{ //Open new file for writing purpose:
using (StreamWriter writer = new StreamWriter(New))
{ //Read all line till end.
while ((line = reader.ReadLine()) != null)
{ //if found "Line_to_delete", ignore the line:
if (String.Compare(line, line_to_delete) == 0)
continue;
//and write other all line into next file:
writer.WriteLine(line);
}
}
}
//read all text from New file:
using (StreamReader sr2 = new StreamReader(New))
{
string chr;
while ((chr = sr2.ReadLine()) != null)
{
Console.WriteLine("From New File: => " + chr);
}
}
Console.ReadKey();
}
}
}
Delete Data from the file:
From Old File: => My Name is Omar
From Old File: => My Name is InfoBrother
From New File: => My Name is InfoBrother
Move and Delete Method:
In order to delete some data from the file, We copy all data into the new file except the data that we want to delete. so we delete the old file and can rename new file.
File.Delete(Old);
File.Move("New", "Old");