HtmlTextWriter没有';处理后不冲洗

本文关键字:处理 没有 HtmlTextWriter | 更新日期: 2023-09-27 18:01:12

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

        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

提前谢谢。

HtmlTextWriter没有';处理后不冲洗

这是HtmlTextWriter中的一个错误。您应该制作一个独立的测试用例,并使用Microsoft Connect进行报告。CloseDispose的行为似乎不同,这一点没有记录在案,而且极不寻常。我在MSDN上也找不到任何说明HtmlTextWriter是否拥有底层textwriter的文档;也就是说,它会处理底层的文本编写器还是必须处理?

编辑2:HtmlTextWriter上的MSDN页面声明它继承(而不是重写(虚拟Dispose(bool)方法。这意味着当前的实现显然不能用using块来清理。作为一种变通方法,请尝试以下操作:

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默认情况下创建而不是追加,并且默认情况下也使用不带BOM的UTF8。

祝你好运,别忘了报告这个错误!

您不需要在using语句中有try{}Finally{}块,因为这将为您处理对象。

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