C# close StreamWriter

本文关键字:StreamWriter close | 更新日期: 2023-09-27 18:14:44

我试图关闭我创建的文本文件,然后将其读取回HTMLDocumentClass。

代码

StreamWriter outfile = 
    new StreamWriter(StripHTMLComps.Properties.Settings.Default.TempFileName);
outfile.Write(HTML);
outfile.Close();
HTMLDocumentClass doc = null;
doc = new HTMLDocumentClass();
IPersistFile persistFile = (IPersistFile)doc;
persistFile.Load(StripHTMLComps.Properties.Settings.Default.TempFileName, 0);
GC.SuppressFinalize(persistFile);
int start = Environment.TickCount;
while (doc.readyState != "complete")
{
    if (Environment.TickCount - start > 10000)
    {
    }
}

文档显示正在加载,但从未完成,我认为它认为文档仍在被另一个进程使用。

任何想法?

C# close StreamWriter

将字符串的创建包装在using语句中,以确保正确的处理(其中一部分将释放文件句柄-感谢@Adam Houldsworth):

using(StreamWriter outfile = new StreamWriter(StripHTMLComps.Properties.Settings.Default.TempFileName))
{
   outfile.Write(HTML);
   // outfile.Close(); // not needed, as the disposal will close the file.
}
// read the file now

我相信这个HTMLDocumentClass来自于WebBrowser。

我不确定你是否可以在没有浏览器控制的情况下使用,但如果可以,你不给它CPU周期来处理文件。

尝试在某处添加Application.DoEventsSleep

如果这不起作用,在你的表单中添加一个WebBrowser,让它加载html,并使用浏览器公开的对象。

如果你只是对解析html树感兴趣,看看html敏捷包

对我来说有太多的假设

using(FileStream fs = new FileStream(SomeName,...))
{
  StreamWriter s = new Streamwriter(fs);
  s.Write(HTML);
  s.Flush();
}

现在应该可以使用了。我有一个策略,总是打开/创建文件与FileStream使用明确的权限请求。如果有什么不正确的地方,你希望它掉下来,而不是20分钟后的代码和10码深。另一件要考虑的事情是为什么你需要HTMLDocumentClass,它是一个用于web浏览器控件的com对象的helper包装器,并且充满了奇怪。

不能确认这一点,但我看到一个报告,为了得到文档状态完成,你必须调用DoEvents在你的while未完成循环。

有类似问题的人