Created
December 8, 2023 10:47
-
-
Save JeremieLitzler/fb0fb0ec22225947e8bb28817d2ac314 to your computer and use it in GitHub Desktop.
Make sure the file is what it seems...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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