Recipe 12.25. Reading from a File at a Specific Position


Problem

You need to access content at a specific byte position in a file.

Solution

Use the Seek() method of a stream to relocate the current position of the stream:

 Dim oneByte As Byte Dim fileData As New IO.  FileStream(filePath, _    IO.FileMode.Open, IO.FileAccess.Read) ' ----- Jump to byte 1000 and read what's there. fileData.Seek(1000, IO.SeekOrigin.Begin) oneByte = fileData.ReadByte( ) 

Discussion

The Seek() method lets you quickly adjust your position in the file. The second argument specifies how the movement is to occur using one of the System.IO.SeekOrigin enumeration values:


SeekOrigin.Begin

The offset indicates a forward position from the beginning of the file. The first byte in the file is position 1.


SeekOrigin.Current

The offset indicates a position relative to the current position in the file. Positive offsets move forward; negative offsets move backward.


SeekOrigin.End

The offset indicates a position relative to the end of the file. Positive offsets move forward beyond the end of the file; negative offsets move backward from the end of the file.

If you position the current position past the end of the file, the next data you write to the file will fill in all the unwritten space between the current end of the file and your new data. If you attempt to read past the end of the file, an exception occurs. You cannot set the current position to a place before the beginning byte of a file.

To determine the current byte position, access the stream's Position property.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net