上传,保存并读取word(.docx)文件c#

时间:2016-02-27 09:37:27

标签: c# asp.net-mvc-4 ms-word

我需要在我的mvc 4站点服务器上保存microsoft word文件。我目前正在做的是使用以下代码保存.docx文件:

path = Path.Combine(Server.MapPath(subPath), System.IO.Path.GetFileName("story_chapter" + DateTime.Now.ToBinary() + ".docx"));
chapFile.SaveAs(path);

并使用以下代码打开文档:

Application word = new Application();
Document doc = new Document();

((_Document)doc).Close();
((_Application)word).Quit();

List<string> data = new List<string>();
try
{
     object fileName = path;
     // Define an object to pass to the API for missing parameters
     object missing = System.Type.Missing;
     doc = word.Documents.Open(ref fileName,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing);

     String read = string.Empty;
     for (int i = 0; i < doc.Paragraphs.Count; i++)
     {
          string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
          if (temp != string.Empty)
                 data.Add(temp);
     }
  }
  catch (Exception)
  {

  }
  finally {

       ((_Document)doc).Close();
       ((_Application)word).Quit();
  }
事实是,我能够保存文件很好,一次,文件也被读取并成功显示。但后来,我开始收到类似&#34; doc已在normat.doc&#34;中打开的错误。或类似的东西,程序卡在以下一行:

doc = word.Documents.Open(ref fileName,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing, ref missing,
             ref missing, ref missing, ref missing);

我已经推断出可能是以错误的方式保存文件。任何帮助将不胜感激。

0 个答案:

没有答案