2012-01-20 85 views
3

我有一個帶有瀏覽和提交按鈕的視圖。當用戶單擊瀏覽時,可以瀏覽.doc或.docx文件,以及何時點擊提交按鈕,所選文件的文本應該填充在同一視圖的文本框中。 以下是我在TextBox中讀取和顯示文本的代碼。如何在Asp.Net MVC3中讀取.doc和.docx文件並在文本框中顯示

  string filePath =null,docText=null; 
      foreach (string inputTagName in Request.Files) 
      { 
       HttpPostedFileBase Infile = Request.Files[inputTagName]; 
       if (Infile.ContentLength > 0 && (Path.GetExtension(Infile.FileName) == ".doc")) 
       { 
        filePath = Path.Combine(
        AppDomain.CurrentDomain.BaseDirectory, 
        Path.GetFileName(Infile.FileName)); 
        if (System.IO.File.Exists(filePath)) 
        { 
         System.IO.File.Delete(filePath); 
        } 
        Infile.SaveAs(filePath); 
       } 
       if (filePath != null) 
       { 

        docText = System.IO.File.ReadAllText(filePath); 

       } 
       ViewBag.displayTextInTextBox= docText; 
      } 
      return View(); 

下面是我查看代碼

<input type="text" id="test1" name="test" value="@ViewBag.displayTextInTextBox"> 

其顯示特殊字符(如本ࡱ)而非.DOC/.DOCX文檔中的文本。 我是不是正在讀取文件,或者在我的代碼中存在什麼問題。

回答

2

那麼山姆你可以看到我的問題here,正如我之前也問過的,如果你能找到它有用。 其實對於這種類型的問題,你需要探索自己的類,並使用它accune給你。 這個答案會給你基本的休息你必須做的。

-2

非常感謝您的朋友的幫助。 下面是我做了什麼,它使用的MSWord的COM對象解決問題,

Microsoft.Office.Interop.Word.ApplicationClass wordApp = new 

    Microsoft.Office.Interop.Word.ApplicationClass(); 
        string filePath1 = filePath; 
        object file = filePath1; 
        object nullobj = System.Reflection.Missing.Value; 

    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref file, 
       ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
       ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
                   ref nullobj); 
       Microsoft.Office.Interop.Word.Document doc1 = wordApp.ActiveDocument; 
       string m_Content = doc1.Content.Text; 
       ViewBag.test = m_Content; 
       doc.Close(ref nullobj, ref nullobj, ref nullobj); 

林。 希望這是最好的可能的方式來做到這一點。

+3

如前所述,這是不建議的。 http://support.microsoft.com/kb/257757 Microsoft目前不推薦並不支持從任何無人蔘與的非交互式客戶端應用程序或組件(包括ASP,ASP.NET,DCOM,和NT服務),因爲Office在此環境中運行時可能會出現不穩定的行爲和/或死鎖。 – KMan

相關問題