Unable to read word file in mvc 4

0

I'm using following code to read word file uploaded on the (local) website.

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;
}

This is the error:

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

I'm calling this function from my controller. If I'm reading the word file wrong way, what's the right way?

asp.net-mvc-4
ms-word
file-read
asked on Stack Overflow Feb 28, 2016 by Tahreem Iqbal

1 Answer

0

Don't close Word before you start doing something:

Remove line 6 and 7:

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

You already do that in the finaly section, so no need to put it back at the end.

answered on Stack Overflow Feb 28, 2016 by Maarten van Stam

User contributions licensed under CC BY-SA 3.0