Client side
<asp:FileUpload runat="server" ID="fileUploader" accept=".pdf,.docx"/> <asp:RegularExpressionValidator ID="fileUploaderV" runat="server" ControlToValidate="fileUploader" ErrorMessage="Only .pdf, .docx formats are allowed" ValidationExpression="(.+\.([Pp][Dd][Ff])|.+\.([Dd][Oo][Cc][Xx]))" Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
Server side
using System.Runtime.InteropServices; [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)] static extern int FindMimeFromData (IntPtr pBC, [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer, int cbSize, [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved); public static string getMimeFromFile(HttpPostedFile file) { IntPtr mimeout; int MaxContent = (int)file.ContentLength; if (MaxContent > 4096) MaxContent = 4096; byte[] buf = new byte[MaxContent]; file.InputStream.Read(buf, 0, MaxContent); int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0); if (result != 0) { Marshal.FreeCoTaskMem(mimeout); return ""; } string mime = Marshal.PtrToStringUni(mimeout); Marshal.FreeCoTaskMem(mimeout); return mime.ToLower(); } }