Reputation: 33
I'm trying to send a Word document (generated in ASP .NET server and Microsoft.Office.Interop.Word) to client side, but everytime I try to open in client side using IE9, it says that it can't open it because it's corrupt, but if I try to save it and open it, it works fine. So where's the problem?
Here's the code:
string nombreDoc = @"C:\tempDocs\Test.doc";
generateIndex(nombreDoc); //this is an internal operation using Interop.Word
FileStream sourceFile = new FileStream(nombreDoc, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Cache.SetNoServerCaching();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-word.document";
HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=Test.doc");
HttpContext.Current.Response.BinaryWrite(getContent);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
File.Delete(nombreDoc);
I have tried to use WriteFile instead of BynaryWrite and the problem persists.
Upvotes: 0
Views: 1782
Reputation: 7215
This is usually because your server has output compression enabled. Basically, your server is trying to GZip the binary document before writing to the output stream. Google will show you how to verify if compression is turned on and how to disable it if it is.
Upvotes: 1
Reputation: 1415
All though my reply might not answer your question completely, but I had been with another problem with ASP.Net & Office Automation. I learned the hard way that its not recommended: Microsoft support
What I did was I made a Windows service instead, which used to create a Word document like the way you are trying to do and make a file on server. The Service would then write the path of the file in database & ASP.Net page will send that file for download. Basically, avoid Office Automation via ASP.Net
Upvotes: 1
Reputation: 411
Change the content type to octet-stream, and revert to using WriteFile instead of BinaryWrite
Response.ContentType = "application/octet-stream";
Upvotes: 1