XDev
XDev

Reputation: 155

How to get file extension from bytes[]

I'm working on a c# project, I created a method that will receive a file as bytes value byte[] parameter.

Method

public static FileEncryptionModel Encrypt(byte[] Filebytes)
{
       //Some code here
}

the question is how can I know the file extension just from its bytes? thank you.

Upvotes: 2

Views: 5633

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

There is no foolproof way to achieve this. Take a look at the list of file signatures here: https://en.m.wikipedia.org/wiki/List_of_file_signatures

As mentioned here: https://en.m.wikipedia.org/wiki/File_format#Magic_number

Originally, this term was used for a specific set of 2-byte identifiers at the beginnings of files, but since any binary sequence can be regarded as a number, any feature of a file format which uniquely distinguishes it can be used for identification.

Your best bet is to store the file type along with the byte array.

You can try the magic number approach, but how could you know an html file from any other text file?

Upvotes: 4

Related Questions