Random Access Files
You can also access the contents of a file in random order. One way to do this is to use the Seek( ) method defined by FileStream. This method allows you to set the file position indicator (also called the file pointer or simply the current position) to any point within a file.
The method Seek( ) is shown here:
long Seek(long offset, SeekOrigin origin)
Here, offset specifies the new position, in bytes, of the file pointer from the location specified by origin. The origin will be one of these values, which are defined by the SeekOrigin enumeration:
SeekOrigin.Begin : | Seek from the beginning of the file. |
SeekOrigin.Current : | Seek from the current location. |
SeekOrigin.End : | Seek from the end of the file. |
After a call to Seek( ), the next read or write operation will occur at the new file position. The new position is returned. If an error occurs while seeking, an IOException is thrown. If the underlying stream does not support position requests, a NotSupportedException is thrown. Other exceptions are possible.
Here is an example that demonstrates random access I/O. It writes the uppercase alphabet to a file and then reads it back in non-sequential order.
Example
using System; using System.IO; namespace ConsoleApplication1 { class RandomAccessDemo { static void Main() { FileStream f = null; char ch; try { f = new FileStream("random.dat", FileMode.Create); // Write the alphabet. for (int i = 0; i < 26; i++) f.WriteByte((byte)('A' + i)); // Now, read back specific values. f.Seek(0, SeekOrigin.Begin); // seek to first byte ch = (char)f.ReadByte(); Console.WriteLine("First value is " + ch); f.Seek(1, SeekOrigin.Begin); // seek to second byte ch = (char)f.ReadByte(); Console.WriteLine("Second value is " + ch); f.Seek(4, SeekOrigin.Begin); // seek to 5th byte ch = (char)f.ReadByte(); Console.WriteLine("Fifth value is " + ch); Console.WriteLine(); // Now, read every other value. Console.WriteLine("Here is every other value: "); for (int i = 0; i < 26; i += 2) { f.Seek(i, SeekOrigin.Begin); // seek to ith character ch = (char)f.ReadByte(); Console.Write(ch + " "); } } catch (IOException exc) { Console.WriteLine("I/O Error\n" + exc.Message); } finally { if (f != null) f.Close(); } Console.WriteLine(); } } }