【发布时间】:2016-05-04 05:52:56
【问题描述】:
我正在用 C# 编写一个插件。我在Stringwriter 中有一个 html,我正在尝试根据我在 SO 和网络上其他地方研究过的其他示例将它输出为 Word 文档。比如这样:Exporting data from c# to word document和http://www.codeproject.com/Questions/196851/export-an-html-to-word-document-with-fixed-headers
对于我的一生,我无法弄清楚为什么我会在出现HttpContext 的第一行出现 NullReference 异常(实际上如何处理它是我所坚持的)。
代码如下:
using System.Web;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application//ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", @"attachment; filename=D:\WORK_ORDER.doc");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF32;
HttpContext.Current.Response.Charset = "UTF-16";
// HttpContext.Current.EnableViewState = false;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
HttpContext.Current.Response.Output.Write(swSource.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
我相信这太简单了。有人可以指出我在这里缺少什么吗?谢谢。
更新:我已经发布了堆栈跟踪,但它没有提供信息,而且很长。附加信息更能说明问题:
附加信息:对象引用未设置为对象的实例。
所有类似的例子都只显示了这段代码,没有实例化,所以我不知道怎么做,所以我很感激一些建议。
更新:
根据批准的答案,导入参考库System.Web 并不意味着您可以在非网络应用程序中使用此HttpContext 对象。
请参阅下面发布的我的解决方案作为答案。
【问题讨论】:
-
你究竟是从哪里得到 NullReferenceException 的?
-
就像 Manfred 所问的,能否请您显示堆栈跟踪?
-
swSource来自哪里? -
旁注:HTML 不是 DOC……和 UTF32/UTF16/UTF8 不是一回事……
-
NullReference 异常在第一行:
HttpContext.Current.Response.Clear();