Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to download docx file using C#

Tags:

c#

download

docx

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.

like image 563
JulyOrdinary Avatar asked Aug 23 '13 07:08

JulyOrdinary


1 Answers

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().

like image 88
Roy Dictus Avatar answered Oct 15 '22 06:10

Roy Dictus