C#: Check if a file is an executable.

Posted May 18th, 2013


The following is a function to check the first two bytes to see if they match "MZ" marking it as an executable.

bool CheckIsExecutable(string filePath)
{
    var firstBytes = new byte[2];
    using(var fileStream = File.Open(filePath, FileMode.Open))
    {
        fileStream.Read(firstBytes, 0, 2);
    }
    return Encoding.UTF8.GetString(firstBytes) == "MZ";
}