Reputation: 119
I am creating a docx file with my app, and I get stuck with the Response.End()
. I get this error:
Thread was being aborted
I get this error, but the file is still created anyway. When I try to open the file it's always corrupted. I am not having any success writing the .docx
file. Please let me know what I am doing wrong.
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "mydoc.docx"));
HttpContext.Current.Response.BinaryWrite(ourString);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
Upvotes: 0
Views: 593
Reputation: 4381
Note, you should not place Response.End
inside the try-catch block because it's expected that it will throw that exception.
See the HttpResponse.End method's remarks:
To mimic the behavior of the End method in ASP, this method tries to raise a ThreadAbortException exception.
You can avoid this by using the following:
var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;
response.AddHeader("Content-Disposition", "attachment;filename=mydoc.docx");
response.OutputStream.Write(ourString, 0, ourString.Length);
response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Note, in the above code I'm presuming that your ourString
variable is byte array because you were passing it to the BinaryWrite
method in your snippet code.
However, this name leads me to believe that you have just converted your string
to byte[]
, is that correct?
If it is, note that this is not a valid DOCX file, DOCX format is not a plain text, you need to write it correctly using Office Open XML format (WordprocessingML).
Upvotes: 2