2014-01-11 36 views
1

我需要一個函數來檢查HttpPostedFileBase是否是一個word文檔。我不想檢查文件擴展名,因爲可以由用戶更改。Asp.net檢查HttpPostedFileBase是否是一個Word文檔

我試着讀取以PK(例如,PDF文件以%PDF開頭)開頭的二進制數據的標題信息,但我不知道我是否可以依賴該信息。

[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); 
} 
+0

如何使用Microsfot.Office DLL來檢查它?打開[http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.documents.open.aspx]方法可用於打開現有文檔。這應該告訴你,如果這是一個有效的文件? – SridharVenkat

+0

你可以在這裏找到一些幫助:http://msdn.microsoft.com/en-us/library/gg615596(v = office.14).aspx –

+0

http://stackoverflow.com/questions/58510/using-net - 如何找到這種MIME類型的文件基於文件簽名/ 9435701 –

回答

相關問題