代码之家  ›  专栏  ›  技术社区  ›  gremo

Webbrowser.DocumentStream或Webbrowser.DocumentText不工作?

  •  2
  • gremo  · 技术社区  · 14 年前

    我不明白为什么这些简单的代码行根本不起作用:

    // 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;
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   Jon Skeet    14 年前

    你保存到流中,把“光标”放在末尾。。。然后把它交给浏览器,我怀疑它是从当前位置读取的。尝试添加:

    stream.Position = 0;
    

    就在最后一行之前。

    编辑:好吧,你说没用。。。这是一个简短但完整的程序,对我有用。试试这个,看看它是否适合你——如果适合,看看你能不能找出你的代码和这个的区别:

    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;
        }
    }
    
        2
  •  3
  •   tntwyckoff    11 年前

    这是一个老问题,但是……我今天已经和它斗争了一段时间,直到我隔离了影响web浏览器控件的这行代码并将其注释掉,它才起作用:

    AllowNavigation = false;
    

    ……显然这是真的。你可以把其他一切都做好,这会阻止它工作。