Asp.net mvc 3 如何在Asp.NETMVC3中读取.doc和.docx文件并在文本框中显示

Asp.net mvc 3 如何在Asp.NETMVC3中读取.doc和.docx文件并在文本框中显示,asp.net-mvc-3,Asp.net Mvc 3,我有一个带有浏览和提交按钮的视图。当用户单击浏览时,可以浏览.doc或.docx文件,当单击提交按钮时,所选文件的文本应填充在同一视图的文本框中。 下面是我在文本框中读取和显示文本的代码 string filePath =null,docText=null; foreach (string inputTagName in Request.Files) { HttpPostedFileBase

我有一个带有浏览和提交按钮的视图。当用户单击浏览时,可以浏览.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文档中的文本。
我是不是读错了文件,或者我的代码有什么问题。

山姆,你可以看到我的问题,正如我之前也问过的,如果你觉得它有用的话。 实际上,对于这种类型的问题,你需要探索自己的课程,并根据自己的需要使用它。
此ans将为您提供所需的基本休息。

而不是使用Word自动化,这需要在您的服务器上安装Word(这可能不是一个好主意)。我将使用OpenXML SDK从Word文档中提取信息:


请注意,这不适用于.doc文件,只适用于docx。

非常感谢朋友们的帮助。 下面是我所做的,它解决了这个问题

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);
我正在使用MSWord的COM对象。
希望这是最好的方法。

如前所述,完全不建议这样做。Microsoft目前不建议也不支持从任何无人值守、非交互式客户端应用程序或组件(包括ASP、ASP.NET、DCOM和NT服务)自动化Microsoft Office应用程序,因为在该环境中运行Office时,Office可能会表现出不稳定的行为和/或死锁。