Webbrowser.DocumentStream or Webbrowser.DocumentText not working?

19,261

Solution 1

You're saving to the stream, leaving the "cursor" positioned at the end... and then giving it to the browser, which I suspect is reading from the current location. Try adding:

stream.Position = 0;

just before the last line.

EDIT: Okay, you say it's not working... here's a short but complete program which works for me. Try this and see if it works for you - and if it does, see if you can work out the difference between your code and this:

using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

class Test
{
    [STAThread]
    static void Main()
    {
        Form form = new Form();
        WebBrowser browser = new WebBrowser();
        browser.Dock = DockStyle.Fill;
        form.Controls.Add(browser);
        form.Load += delegate { SetDocumentStream(browser); };

        Application.Run(form);
    }

    static void SetDocumentStream(WebBrowser browser)
    {
        string text = "<html><head><title>Stuff</title></head>" +
            "<body><h1>Hello</h1></body></html>";
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        MemoryStream ms = new MemoryStream();
        ms.Write(bytes, 0, bytes.Length);
        ms.Position = 0;
        browser.DocumentStream = ms;
    }
}

Solution 2

This is old, but....i was battling this for a while today and it didn't work until i isolated this line of code affecting the web browser control and commented it out:

AllowNavigation = false;

...so evidently this needs to be true. you can have everything else right and this will prevent it from working.

Share:
19,261
gremo
Author by

gremo

Updated on June 05, 2022

Comments

  • gremo
    gremo almost 2 years

    I can't figure out why this simple lines of code simply doesn't work:

    // Bulding tree
    var declaration = new XDeclaration("1.0", "UTF-8", "yes");
    var root = new XElement("root");
    
    // Adding elements to document
    var doc = new XDocument(declaration, root);
    
    // Salve the stream
    var stream = new MemoryStream();
    doc.Save(stream);
    
    // Update WebBrowser control
    webBrowser1.DocumentStream = stream;