Skuami
Skuami

Reputation: 1614

Read binary file in C# from specific position

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.

Upvotes: 6

Views: 26494

Answers (4)

Petar Ivanov
Petar Ivanov

Reputation: 93000

using (FileStream sr = File.OpenRead("someFile.dat"))
{
    sr.Seek(100, SeekOrigin.Begin);
    int read = sr.ReadByte();
    //...
}

Upvotes: 15

Yehuda G.
Yehuda G.

Reputation: 171

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

Upvotes: 10

Rasel
Rasel

Reputation: 15477

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

Upvotes: 0

Boas Enkler
Boas Enkler

Reputation: 12557

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

Upvotes: 1

Related Questions