首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HtmlTextWriter在处理时不刷新吗?

HtmlTextWriter在处理时不刷新吗?
EN

Stack Overflow用户
提问于 2011-07-06 19:38:25
回答 3查看 1.5K关注 0票数 1

我需要写一些有风格的文本(比如颜色,字体),所以我决定使用html。我发现HtmlTextWriter是一个用于编写html文件的类。然而,我发现我必须手动关闭或刷新它,否则不会向文件中写入任何内容。为什么会这样呢?(using语句应该在代码块完成时将其释放)

代码语言:javascript
复制
        using (HtmlTextWriter htmlWriter = new HtmlTextWriter(new StreamWriter(
            Path.Combine(EmotionWordCounts.FileLocations.InputDirectory.FullName, fileName),
            false, Encoding.UTF8)))
        {
            try
            {

                htmlWriter.WriteFullBeginTag("html");
                htmlWriter.WriteLine();
                htmlWriter.Indent++;

                htmlWriter.WriteFullBeginTag("body");
                htmlWriter.WriteLine();
                htmlWriter.Indent++;

                // write something using WriteFullBeginTag and WriteEndTag
                // ...

            } //try
            finally
            {
                htmlWriter.Indent--;
                htmlWriter.WriteEndTag("body");
                htmlWriter.WriteLine();

                htmlWriter.Indent--;
                htmlWriter.WriteEndTag("html");
                htmlWriter.Close(); // without this, the writer doesn't flush
            }
        } //using htmlwriter

提前谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-06 19:58:14

这是HtmlTextWriter中的一个错误。您应该制作一个自包含的测试用例和report it using Microsoft Connect。看起来CloseDispose的行为是不同的,这是没有文档记录的,也是非常不寻常的。我在MSDN上也找不到任何说明HtmlTextWriter takes ownership of the underlying textwriter是否存在的文档;也就是说,它是否会处理底层的文本写入器,或者你必须这样做?

MSDNEdit2: HtmlTextWriter上的页面声明它继承(而不是覆盖)虚拟的Dispose(bool)方法。这意味着当前的实现显然不能使用using块进行清理。作为一种解决方法,请尝试执行以下操作:

代码语言:javascript
复制
using(var writer = ...make TextWriter...) 
using(var htmlWriter = new HtmlTextWriter(writer)) {

    //use htmlWriter here...

} //this should flush the underlying writer AND the HtmlTextWriter

// although there's currently no need to dispose HtmlTextWriter since
// that doesn't do anything; it's possibly better to do so anyhow in 
// case the implementation gets fixed

顺便说一下,new StreamWriter(XYZ, false, Encoding.UTF8)等同于new StreamWriter(XYZ)。默认情况下,StreamWriter会创建而不是附加。默认情况下,它也会使用没有物料清单的UTF8。

祝你好运--别忘了report the bug

票数 2
EN

Stack Overflow用户

发布于 2011-07-06 19:52:47

您不需要在using语句中包含try{} Finally {}块,因为这将为您释放对象。

票数 0
EN

Stack Overflow用户

发布于 2011-07-06 19:59:41

我怀疑原因是HtmlTextWriter没有为TextWriter的protected virtual void Dispose( bool disposing )方法提供调用Close()的重写,所以,你是对的,你需要自己做这件事-TextWriter的实现是空的。正如aspect所指出的那样,您不需要在using语句中使用try finally块。正如Eamon Nerbonne所指出的,这肯定是一个框架错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6595742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档