I need a function which checks if the HttpPostedFileBase
is a word document. I don't want to check against file extension because that can be changed by the user.
I tried to read the Header information of the binary data, which starts with PK
(for example, PDF files starts with %PDF
), but i don't know if i can rely upon that.
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
string header = null;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
char[] buffer = new char[5];
sr.Read(buffer, 0, 4);
header =
string.Format("{0}{1}{2}{3}{4}", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);
}
}
if (header.StartsWith("%PDF"))
{
// PDF Document
}
if (header.StartsWith("PK"))
{
// Microsoft Word Document ?
}
return Json(new { }, JsonRequestBehavior.AllowGet);
}