【问题标题】:Generated Docx File is Corrupt - C#生成的 Docx 文件已损坏 - C#
【发布时间】:2020-12-29 14:32:30
【问题描述】:

我正在使用我的应用程序创建一个 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();

【问题讨论】:

  • 请提供可执行代码。

标签: c# download response mime-types docx


【解决方案1】:

注意,您不应该将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 变量是字节数组,因为您在 sn-p 代码中将它传递给了 BinaryWrite 方法。

但是,这个名字让我相信你刚刚将你的string 转换为byte[],对吗?

如果是,请注意这不是有效的 DOCX 文件,DOCX 格式不是纯文本,您需要使用 Office Open XML 格式(WordprocessingML)正确写入。

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-24
      • 2012-07-21
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      相关资源
      最近更新 更多