Unable to download docx file using C#

JulyOrdinary picture JulyOrdinary · Aug 23, 2013 · Viewed 13.4k times · Source

This is my code and I am trying since hours to download the docx file. but no success. Where I might be lagging, need a slight hint.

if (File.Exists(sTempPath + sCreateFileName))
            {
                FileInfo file =new FileInfo(sTempPath + sCreateFileName);
                Response.ClearContent();
                // LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                // Add the file size into the response header
                Response.AddHeader("Content-Length", file.Length.ToString());
                // Set the ContentType                        
                Response.ContentType = ReturnExtension(file.Extension.ToLower());
                // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
                Response.TransmitFile(sTempPath + sCreateFileName);
                // End the response
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            } 

and Return content type gives, content type for docx file:

"application/ms-word"

where if sTempPath+sCreateFileName is the whole path of the file.

Update: I tried content type:

application/vnd.openxmlformats-officedocument.wordprocessingml.document

This is not working.

Answer

Roy Dictus picture Roy Dictus · Aug 23, 2013

The correct MIME type for DOCX is not application/msword but application/vnd.openxmlformats-officedocument.wordprocessingml.document.

The MIME type you specified is for DOC files.

Also you might want to put a Response.Flush() and a Response.End() instead of the CompleteRequest().