我正在用我的应用程序创建一个docx文件,但我被Response.End()
卡住了。我得到这个错误:
线程被中止
我收到这个错误,但文件仍然是创建的。当我试图打开文件时,它总是被破坏了。我没有成功地编写.docx
文件。请让我知道我做错了什么。
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();
注意,您不应该将Response.End
放置在try-catch块内,因为预计它会引发该异常。请参阅HttpResponse.End方法的备注:
为了模仿ASP中End方法的行为,此方法尝试引发ThreadAbortException异常。
您可以使用以下方法来避免这种情况:
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();
注意,在上面的代码中,我假设您的ourString
变量是字节数组,因为您在代码片段中将其传递给BinaryWrite
方法。
然而,这个名字让我相信你刚刚将string
转换为byte[]
,对吗?
如果是,请注意这不是一个有效的DOCX文件,DOCX格式不是纯文本,您需要使用Office Open XML格式(WordprocessingML(正确编写它。