Webbrowser.DocumentStream或Webbrowser.DocumentText无法正常工作?

gre*_*emo 2 c# browser stream linq-to-xml webbrowser-control

我无法弄清楚为什么这些简单的代码行根本不起作用:

// 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;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

您将保存到流中,将"光标"保留在末尾...然后将其提供给浏览器,我怀疑它是从当前位置读取的.尝试添加:

stream.Position = 0;
Run Code Online (Sandbox Code Playgroud)

就在最后一行之前.

编辑:好的,你说它不起作用......这是一个简短但完整的程序,对我有用.试试这个,看看它是否适合你 - 如果确实如此,看看你是否能解决你的代码和这个之间的区别:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)