Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read specific bytes of a file

Tags:

c#

file-io

byte

Is there any way to read specific bytes from a file?

For example, I have the following code to read all the bytes of the file:

byte[] test = File.ReadAllBytes(file); 

I want to read the bytes from offset 50 to offset 60 and put them in an array.

like image 272
Ahmed M. Taher Avatar asked Dec 30 '11 11:12

Ahmed M. Taher


People also ask

How do I find specific bytes in Python?

It's simple mathematics: index = (pos*2) with base pos = 1. So first byte is pos=1 and hence index=2 in a zero-based array. ... and then take 10*2 digits to get the 10 bytes. You could use a bit mask to AND the bit shifted value to only get the bits you need.

How do I read an offset file in Python?

Description. Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. There is no return value.

How do I read a binary file in Python?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.

What is file read in Python?

Python File read() Method The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.


1 Answers

Create a BinaryReader, read 10 bytes starting at byte 50:

byte[] test = new byte[10]; using (BinaryReader reader = new BinaryReader(new FileStream(file, FileMode.Open))) {     reader.BaseStream.Seek(50, SeekOrigin.Begin);     reader.Read(test, 0, 10); } 
like image 98
Robert Rouhani Avatar answered Sep 20 '22 22:09

Robert Rouhani