Determine the file type using C#

Viewed 117831

I have a web page that has the file upload component to upload the allowed document types only to my system (images only). I don't want to use the regular expression to determine the file type and using the extension.

Please let me know if there is any other means of determining file types in C#.

8 Answers

It's never a good idea to write your code like that:

string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);

if (fileExt == ".jpeg" || fileExt == ".jpg")
{
    //do what you want with this image
}

The reason of that is because it will give you the extension from the filename. Lets assume that the user is smart enough to change the filename from foo.exe to foo.png and upload it. In this code sample validation will be passed and this is bad for you.

The only appropriate way to identify file type is by checking it magic bytes. According to Wikipedia this term ("magic numbers") 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. This approach offers better guarantees that the format will be identified correctly, and can often determine more precise information about the file. Reference to original post.

Because of that I had the same problem a year ago and I created a library that can help you with that scenario. It's easy to use and with few lines of code you will be safe.

you can use Myrmec to identify the file type, this library use the file byte head. this library avaliable on nuget "Myrmec",and this is the repo, myrmec also support mime type,you can try it. the code will like this :

// create a sniffer instance.
Sniffer sniffer = new Sniffer();

// populate with mata data.
sniffer.Populate(FileTypes.CommonFileTypes);

// get file head byte, may be 20 bytes enough.
byte[] fileHead = ReadFileHead();

// start match.
List<string> results = sniffer.Match(fileHead);
  • Use FileExtensionContentTypeProvider()
[HttpGet]
public string Get(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    if(!provider.TryGetContentType(fileName, out contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;
}
Related