无法在mvc 4中读取word文件

时间:2016-02-28 15:46:04

标签: asp.net-mvc-4 ms-word file-read

我正在使用以下代码来阅读(本地)网站上传的word文件。

List<string> ReadWordFile(string 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();
        }

        return data;
}

这是错误:

The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))

我正在从我的控制器调用此函数。如果我正在以错误的方式阅读word文件,那么正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

在开始做某事之前不要关闭Word:

删除第6行和第7行:

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

你已经在最后一节中做到了这一点,所以最后不需要把它放回去。