6

Is it possible to read a large binary file from a particular position?

I don't want to read the file from the beginning because I can calculate the start position and the length of the stream I need.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
Skuami
  • 1,422
  • 2
  • 14
  • 28
  • All you have to do is change the `Position` property, or use the `Seek` method. Are you worried that the entire file is loaded into memory? – Marlon Jul 13 '11 at 06:27
  • Yes, I dont want to load the entire file into memory. I use the BinaryReader and couldnt find the Seek method. --> BinaryReader.BaseStream.Seek(), thats the solution. ;-) – Skuami Jul 13 '11 at 14:43
  • You won't have to worry about a huge file being loaded into memory. A stream only loads a portion of it at a time. Otherwise we would never be able to open huge files. – Marlon Jul 13 '11 at 18:31

4 Answers4

15
using (FileStream sr = File.OpenRead("someFile.dat"))
{
    sr.Seek(100, SeekOrigin.Begin);
    int read = sr.ReadByte();
    //...
}
dodekja
  • 537
  • 11
  • 24
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
9

According to @shenhengbin answord.

Use BinaryReader.BaseStream.Seek.

using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open)))                                                     
{
    int pos = 50000;
    int required = 2000;

    // Seek to our required position.
    b.BaseStream.Seek(pos, SeekOrigin.Begin);

    // Read the next 2000 bytes.
    byte[] by = b.ReadBytes(required);
}
Yehuda G.
  • 161
  • 1
  • 4
1

Well if you know streams, why not using (File)Stream.Seek(...) ?

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
  • 1
    I use the BinaryStream but I couldnt find the Seek() method. The link from Scott explains how to get the seek method on a binary reader. BinaryReader.BaseStream.Seek(pos, SeekOrigin.Begin); – Skuami Jul 13 '11 at 14:40
0

Of course it is possible.See this here.See the offset.you can read from the offset

Rasel
  • 15,499
  • 6
  • 40
  • 50
  • 1
    Not really, the offset defines the offset for the buffer not for the starting point of the file. I tried this way before I wrote this entry. – Skuami Jul 13 '11 at 14:38