本文介绍了C# - 试图保存HTML到Word在C#中时的HttpContext不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#中的插件。而且我有一个的StringWriter 的HTML,我试图把它输出的基础上我已经在网络上SO等地研究其他样本的Word文档。像这样:导出数据和



有关我的生活我不能弄清楚为什么我得到的第一行的HttpContext 出现NullReference异常(实际上是如何处理这是我坚持什么的)。



下面是代码:



使用的System.Web;

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = TRUE;
HttpContext.Current.Response.ContentType =应用// MS-词;
HttpContext.Current.Response.AddHeader(内容处置,@附件;文件名= 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();



我相信这是太简单了。有人能指出我是缺少在这里?谢谢



更新:我已经张贴的堆栈跟踪,但它是无信息的冗长。附加信息是更能说明问题:



All the similar examples show only this code, no instantiation, so I am at loss how to do this, so I'd appreciate some advice.

Update:

According to the approved answer all that happened, that importing the reference library System.Web does not mean that you can use this HttpContext object in a non-web app.

See my solution posted below as an answer.

解决方案

If I were to guess I'd say your project is a class library or some non web application project.

If this is the case you will not have access to httpcontext and you'll either have to change your project to a web project or you can look at alternative methods of saving your file. For example:Writing Text File to Folder on Desktop

*note I've not tried the suggested solution.

这篇关于C# - 试图保存HTML到Word在C#中时的HttpContext不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 09:09