Hi,

Given below is an example of a C#/C Sharp Random Access File.

using System;
using System.IO;

class MainClass {
  public static void Main() {
    FileStream alphaStr;
    char alphaChr;

    try {
      alphaStr = new FileStream("randomDatFile.dat", FileMode.Create);
    }
    catch(IOException exc) {
      Console.WriteLine(exc.Message);
      return ;
    }

    // Write the alphabet.
    for(int i=0; i < 26; i++) {
      try {
        alphaStr.WriteByte((byte)('A'+i));
      }
      catch(IOException exc) {
        Console.WriteLine(exc.Message);
        return ;
      }
    }

    try {
      alphaStr.Seek(0, SeekOrigin.Begin); // seeking first
      alphaChr = (char) f.ReadByte();
      Console.WriteLine("First value is " + alphaChr);

      alphaStr.Seek(1, SeekOrigin.Begin); // seeking second
      alphaChr = (char) f.ReadByte();
      Console.WriteLine("Second value is " + alphaChr);

      alphaStr.Seek(25, SeekOrigin.Begin); // seeking 26th
      alphaChr = (char) f.ReadByte();
      Console.WriteLine("Last value is " + alphaChr);

      Console.WriteLine();

    }
    catch(IOException exc) {
      Console.WriteLine(exc.Message);
    }

    Console.WriteLine();
    alphaStr.Close();
  }
}

And the output will be…

First value is A
Second value is B
Last value is E

This example shows how you can randomly access data.

🙂

 

2 Comments

  1. siva April 25, 2012 at 9:29 am

    where f is defined?
    what is functionality of f

     
  2. Barniferous August 27, 2013 at 4:05 pm

    Two corrections: Omitted first line in the final try block. Should be:
    BinaryReader f = new BinaryReader(alphaStr);
    Also, last output line should be “Last value is Z”

     

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.