TC.
TC.

Reputation: 4183

Why can't Word directly open my generated docx, but can open it when saved to disk first?

I am generating a *.docx file server-side, that I want to return to the user upon pressing a button. In the button's event handler, I currently generate the document data as a byte[] (called bytes in the following code sample), and return it to the user as follows:

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=Test.docx;");
Response.AddHeader("Content-Length", bytes.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/vnd.ms-word.document.12";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();

This results in the strange behavior with IE that when the user clicks the "open" button when presented with the download, word 2010 fires up and states that "Word experienced an error trying to open the file". If the user choses to save the file somewhere first however, word opens the saved document just fine.

I've experimented with different content-types, caching and encoding options, to no avail. Any clues what could be causing this behavior?

Upvotes: 2

Views: 2492

Answers (3)

TC.
TC.

Reputation: 4183

It turns out that this was a problem with Office 2010's trust settings. Disabling some trust checks resolved the problem:

http://answers.microsoft.com/en-us/office/forum/office_2010-word/word-experienced-an-error-trying-to-open-the-file/07b539fa-c641-e011-9767-d8d385dcbb12

As far as I know, there isn't a way to solve this problem server-side.

Upvotes: 0

Icarus
Icarus

Reputation: 63956

Add Response.End(); on your last line.

Upvotes: 1

Marc B
Marc B

Reputation: 360612

IE is extraordinarily stupid with file downloads. Everything is mediated through the browser's cache. When firing up an external program to load up a file, it's very possible for IE to delete the file from the cache BEFORE word manages to get started and try to access the file.

You're outputting no-cache headers, which definitely tells word to NOT cache the file. This effectively makes the file non-downloadable: IE will download and then instantly delete the file, because it's not supposed to be cached.

Upvotes: 2

Related Questions