JMK
JMK

Reputation: 28059

How do I read the individual bytes of a file

I am trying to determine whether or not a file has been compressed with the GZip protocol.

The consensus seems to be that I need to read the first two bytes of the file, and check that they are equal to 0x1f8b. I have just learned that this is known as a magic number.

How do I, preferably using .Net/C# as this is what I am used to, read the individual bytes of a file?

Thankyou

Upvotes: 0

Views: 292

Answers (3)

d4v3y0rk
d4v3y0rk

Reputation: 345

you could try this...

you might need to use a different variable type for v or you could convert the int...

using (BinaryReader b = new BinaryReader(File.Open("file.bin", FileMode.Open)))
{
    int v = b.ReadByte();
    Console.WriteLine(v);
}

Upvotes: 2

Maciek Talaska
Maciek Talaska

Reputation: 1638

The easiest way to read the two (first) bytes of a file is to open a FileStream and then read just the two bytes:

FileStream fs = new FileStream( "D:\\path_to_file\file.ext", FileMode.Open);
int value = fs.ReadByte();
...

Of course you should check if file exist, catch the exception if app is not running with enough permission to read the file, close the stream (access to file) when you're done with it...

It may be more convenient to use FileStream's Read method (which allows you to read many bytes at once). Please note, that there is also asynchronous equivalent of this method available.

Upvotes: 1

Usually in common x86, char is a byte-long data type, so reading first two chars of the file will do.

Upvotes: 0

Related Questions