Read binary file in C# from specific position
Asked Answered
E

4

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.

Episcopalism answered 13/7, 2011 at 6:10 Comment(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?Fronia
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. ;-)Episcopalism
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.Fronia
R
15
using (FileStream sr = File.OpenRead("someFile.dat"))
{
    sr.Seek(100, SeekOrigin.Begin);
    int read = sr.ReadByte();
    //...
}
Rexford answered 13/7, 2011 at 6:15 Comment(0)
W
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);
}
Wispy answered 21/5, 2018 at 16:32 Comment(0)
H
1

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

Hattie answered 13/7, 2011 at 6:13 Comment(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);Episcopalism
I
0

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

Indolence answered 13/7, 2011 at 6:13 Comment(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.Episcopalism

© 2022 - 2024 — McMap. All rights reserved.