我需要写一些有风格的文本(比如颜色,字体),所以我决定使用html。我发现HtmlTextWriter是一个用于编写html文件的类。然而,我发现我必须手动关闭或刷新它,否则不会向文件中写入任何内容。为什么会这样呢?(using语句应该在代码块完成时将其释放)
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提前谢谢。
发布于 2011-07-06 19:58:14
这是HtmlTextWriter中的一个错误。您应该制作一个自包含的测试用例和report it using Microsoft Connect。看起来Close和Dispose的行为是不同的,这是没有文档记录的,也是非常不寻常的。我在MSDN上也找不到任何说明HtmlTextWriter takes ownership of the underlying textwriter是否存在的文档;也就是说,它是否会处理底层的文本写入器,或者你必须这样做?
MSDNEdit2: HtmlTextWriter上的页面声明它继承(而不是覆盖)虚拟的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会创建而不是附加。默认情况下,它也会使用没有物料清单的UTF8。
祝你好运--别忘了report the bug!
发布于 2011-07-06 19:52:47
您不需要在using语句中包含try{} Finally {}块,因为这将为您释放对象。
发布于 2011-07-06 19:59:41
我怀疑原因是HtmlTextWriter没有为TextWriter的protected virtual void Dispose( bool disposing )方法提供调用Close()的重写,所以,你是对的,你需要自己做这件事-TextWriter的实现是空的。正如aspect所指出的那样,您不需要在using语句中使用try finally块。正如Eamon Nerbonne所指出的,这肯定是一个框架错误。
https://stackoverflow.com/questions/6595742
复制相似问题