Skip to content

Instantly share code, notes, and snippets.

@islaytitans

islaytitans/ValidateMimeType.cs Secret

Last active Aug 29, 2015
Embed
What would you like to do?
Utilise the MimeType validator
private bool ValidateMimeType(HttpPostedFile postedFile)
{
bool valid = false;
try
{
Stream stream = postedFile.InputStream;
var mimeTypeUtil = new MimeTypeUtil();
string mime = mimeTypeUtil.GetMimeType(ReadFully(stream), postedFile.FileName);
valid = PermittedMimeTypes.Contains(mime);
}
catch (Exception ex)
{
Log.Error("Error occurred when determining mime type of file", ex, this);
throw;
}
return valid;
}
private static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private IEnumerable<string> _permittedMimeTypes;
private IEnumerable<string> PermittedMimeTypes
{
get
{
if (_permittedMimeTypes == null)
{
_permittedMimeTypes = new List<string>()
{
MimeType.ImageBmp,
MimeType.ImageGif,
MimeType.ImageJpeg,
MimeType.ImagePng,
};
}
return _permittedMimeTypes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment