C#/C Sharp – Random Access File Example

By | June 12, 2011

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 thoughts on “C#/C Sharp – Random Access File Example

  1. Barniferous

    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”

    Reply

Leave a Reply

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