title: HTML source code from TWebBrowser - How to detect Stream encoding?
body: <p>Based on this question:  <a href="https://stackoverflow.com/questions/10091666/how-can-i-get-html-source-code-from-twebbrowser/10091894">How can I get HTML source code from TWebBrowser</a></p>
  
  <p>If I run <a href="https://stackoverflow.com/a/10091894/937125">this code</a> with a html page that has Unicode code page, the result is gibberish becouse TStringStream is not Unicode in D7. the page might be UTF8 encoded or other (Ansi) code page encoded.</p>
  
  <p>How can I detect if a TStream/IPersistStreamInit is Unicode/UTF8/Ansi?</p>
  
  <p>How do I always return correct result as <strong>WideString</strong> for this function?</p>
  
  <pre><code>function GetWebBrowserHTML(const WebBrowser: TWebBrowser): WideString;
  </code></pre>
  
  <p>If I replace TStringStream with TMemoryStream, and save TMemoryStream to file it's all good. It can be either Unicode/UTF8/Ansi. but I always want to return the stream back as WideString:</p>
  
  <pre><code>function GetWebBrowserHTML(const WebBrowser: TWebBrowser): WideString;
  var
    // LStream: TStringStream;
    LStream: TMemoryStream;
    Stream : IStream;
    LPersistStreamInit : IPersistStreamInit;
  begin
    if not Assigned(WebBrowser.Document) then exit;
    // LStream := TStringStream.Create('');
    LStream := TMemoryStream.Create;
    try
      LPersistStreamInit := WebBrowser.Document as IPersistStreamInit;
      Stream := TStreamAdapter.Create(LStream,soReference);
      LPersistStreamInit.Save(Stream,true);
      // result := LStream.DataString;
      LStream.SaveToFile('c:\test\test.txt'); // test only - file is ok
      Result := ??? // WideString
    finally
      LStream.Free();
    end;
  end;
  </code></pre>
  
  <hr>
  
  <p>EDIT: I found this article - <a href="http://www.delphidabbler.com/articles?article=14&amp;part=1" rel="nofollow noreferrer">How to load and save documents in TWebBrowser in a Delphi-like way</a></p>
  
  <p>Which does exactlly what I need. but it works correctlly only with Delphi Unicode compilers (D2009+). read <a href="http://www.delphidabbler.com/articles?article=14&amp;part=1#conclusion" rel="nofollow noreferrer">Conclusion</a> section:  </p>
  
  <blockquote>
    <p>There is obviously a lot more we could do. A couple of things
    immediately spring to mind. We retro-fit some of the Unicode
    functionality and support for non-ANSI encodings to the pre-Unicode
    compiler code. The present code when compiled with anything earlier
    than Delphi 2009 will not save document content to strings correctly
    if the document character set is not ANSI.</p>
  </blockquote>
  
  <p>The magic is obviously in <code>TEncoding</code> class (<code>TEncoding.GetBufferEncoding</code>). but D7 does not have <code>TEncoding</code>. Any ideas?</p>