How to open a Word document from an ASP.NET application



Introduction

Sometimes we need to open a Microsoft Word document in an ASP.NET application.

This article demonstrates how to open a Word document in an ASP.NET application.

What do we need to open document?

Response.ContentType = "application/vnd.msword.document.12";

The ContentType property specifies the HTTP content type for the response.

If no ContentType is specified, the default is text/HTML.

We could say ContentType is a DocType, so we could set

ContentType by using the code shown below:

        private string GetDocumentMimeType(string fileName)
        {
            //string mimeType = "application/unknown";
            string mimeType = "application/vnd.msword.document.12";
            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();

            return "//" + mimeType;
        }


In an ASP.NET application we need to add the header: Content-Disposition,Content-Length

Content-Disposition: attachment

Body parts designated as containing attachments require user action to be displayed and are normally split out of the message. They are typically stored as files for subsequent access. The optional parameters for this header are: file name, creation-date, modification-date, read-date, and size.

What does the AddHeader method do?

The AddHeader method adds a new HTML header and value to the response sent to the client.