簡體   English   中英

C#關閉StreamWriter

[英]C# close StreamWriter

我試圖關閉我創建的文本文件,然后將其讀回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)
    {
    }
}

該文件說正在加載但從未完成,我相信它認為該文件仍在被另一個進程使用。

有任何想法嗎?

將創建的字符串包裝在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 Agility Pack

對我來說太多的假設

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

現在應該可以使用了。 我有一個始終使用顯式權限請求通過FileStream打開/創建文件的策略。 如果不正確,則希望該位掉下來,而不是二十分鍾后再加深十碼的代碼。要考慮的另一件事是為什么需要HTMLDocumentClass,它是com對象的輔助包裝,可在Web瀏覽器中使用控制,並充滿奇怪。

無法確認這一點,但是我看到一個報告,為了使文檔狀態完成,您必須在未完成循環中調用DoEvents。

遇到類似問題的其他人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM