简体   繁体   中英

open word document corrupt

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.

将内容类型更改为八位字节流,并恢复为使用WriteFile代替BinaryWrite

Response.ContentType = "application/octet-stream";

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM