Skip to content

Instantly share code, notes, and snippets.

@islaytitans

islaytitans/MimeTypeAllowed.cs Secret

Created Sep 24, 2015
Embed
What would you like to do?
Uses the permitted file types and compares the byte array sequence of the uploaded file against them
public FileType MimeTypeAllowed(byte[] file, string fileName, List<FileType> permittedMimeTypes)
{
FileType uploadedFileType = null;
string extension = Path.GetExtension(fileName) != null
? Path.GetExtension(fileName).ToUpper()
: string.Empty;
var matchedByByte = new List<FileType>();
var matchedByByteAndExtension = new List<FileType>();
foreach (var permittedMimeType in permittedMimeTypes)
{
int byteCount = permittedMimeType.ByteArray.Count();
if (file.Take(byteCount).SequenceEqual(permittedMimeType.ByteArray))
{
if (!string.IsNullOrEmpty(permittedMimeType.FileExtension))
{
if (permittedMimeType.FileExtension.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
{
matchedByByteAndExtension.Add(new FileType(permittedMimeType.MimeType, file, extension));
}
}
else
{
matchedByByte.Add(new FileType(permittedMimeType.MimeType, file, extension));
}
}
}
uploadedFileType = matchedByByteAndExtension.Any()
? matchedByByteAndExtension.FirstOrDefault()
: matchedByByte.Any() ? matchedByByte.FirstOrDefault() : null;
return uploadedFileType;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment