It is quite an easy process to upload files from a web browser, but how do you know it is the correct type of document you are asking for?
You can check the file extenstion, but a hacker would just change the file type to another extension, so this is not a fail safe way of checking the file type being uploaded.
Another way which can check for the content of the file being uploaded and look for a signature.
First we will need to hold the signature in a file type, so lets create an enum for them
public enum FileType { Gif = 7173, Jpg = 255216, Png = 13780, Bmp = 6677, TxtAspxAspSql = 239187, XlsDocPpt = 208207, Xml = 6063, Html = 6033, Js = 4742, XlsxZipPptxMmapZip = 8075, Rar = 8297, AccdbMdb = 01, ExeDll = 7790, Bat = 64101, Unknown }
You’ll notice that some file types have the same signature so you need to be a little careful with these files.
Now for the method that will return our file type:
protected FileType IsImageFile(HttpPostedFileBase file) { var fs = new FileStream(file.FileName, FileMode.Open, System.IO.FileAccess.Read); var br = new BinaryReader(fs); string fileclass; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { return FileType.Unknown; } finally { br.Close(); fs.Close(); } foreach (var type in Enum.GetValues(typeof(FileType))) { var l = (int)type; String[] fileType = {l.ToString()}; if (fileType.Any(t => fileclass == t)) { return (FileType)Enum.Parse(typeof(FileType), type.ToString()); } } return FileType.Unknown; }
That is it, all done