Skip to content

Instantly share code, notes, and snippets.

@JeremieLitzler
Created December 8, 2023 10:47
Show Gist options
  • Save JeremieLitzler/fb0fb0ec22225947e8bb28817d2ac314 to your computer and use it in GitHub Desktop.
Save JeremieLitzler/fb0fb0ec22225947e8bb28817d2ac314 to your computer and use it in GitHub Desktop.
Make sure the file is what it seems...
namespace Awesome.Csharp.Utilities.EveryoneNeeds
{
public static class FileMagicNumberHelper
{
public static bool CheckUploadedFileMagicNumber(byte[] file)
{
//No file
if (file == null) return false;
//File contains less than 2 bytes
if (file.Count() < 2) return false;
//Read first byte
var firstByte = file[0].ToString();
//Read second byte
var secondByte = file[1].ToString();
var fileClass = string.Concat(firstByte, secondByte);
var isFileJpg = (fileClass == "255216");
var isFilePdf = (fileClass == "3780");
var isFileDocx = (fileClass == "8075");//valid for docx, dotx and docm.
if (!isFileJpg && !isFilePdf && !isFileDocx)
{
return false;
}
//File is valid!
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment