Detect Executable file or Virus during File Upload

  • Post author:
  • Post category:C# / Security
  • Reading time:1 mins read

Many times we fall in a situation where we have implemented detection of file type based on file extension. It’s pretty easy to do that on both client as well as server side.

But does it guarantees that file uploaded is not actually an “exe” file. Well, anyone can rename an “abc.exe” to “abc.txt” and upload it to your web application which may lead to dangerous results & even security threst.

Here is a more deeper insight to validate the same.

Thumb Rule: All Windows/DOS executables begin with a “magic number”; the word value $5A4D (“MZ or “ZM” in ASCII). 

Below is the C# implementation of this rule to detect it file uploaded is an executable irrespective of the file extension.

public static bool IsExeFile(byte[] FileContent)
var twoBytes = SubByteArray(FileContent, 0, 2);
return ((Encoding.UTF8.GetString(twoBytes) == "MZ")||(Encoding.UTF8.GetString(twoBytes) == "ZM"));

private static byte[] SubByteArray(byte[] data, int index, int length)
byte[] result = new byte[length];
Array.Copy(data, index, result, 0, length);
return result;
(Visited 2,475 times, 1 visits today)