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.

3
  • 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? Commented Jul 13, 2011 at 6: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. ;-) Commented Jul 13, 2011 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. Commented Jul 13, 2011 at 18:31

4 Answers 4

15
using (FileStream sr = File.OpenRead("someFile.dat"))
{
    sr.Seek(100, SeekOrigin.Begin);
    int read = sr.ReadByte();
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

10

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);
}

Comments

1

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

1 Comment

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);
0

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.