Display Images in C# Webbrowsers Design Mode

Veröffentlicht von

The edit mode (or design mode) in C# webbrowser control is an easy way to write your own small WYSIWYG editor. Standard formatting is easy to achive. Displaying images is also not a problem, as long as you work with absolute URLs.

Working with relative URLs usually does not work, as the browser control does not know where the “current HTML file is”.  For example if you have the webbrowser control and switch it to edit mode:
    SetValue(webBrowser.Document.DomDocument, "On", null);
Relative images and other files are not shown.
While this works:
<img src="https://andydunkel.net/wp-content/uploads/2017/12/logo.png">
this does not:
<img src="logo.png">
The trick is to modifiy the HTML file and set the Base URL to the local path where your images are:
string baseUrl = "file:///" + GetApplicationPath().Replace("\\", "/") + "/";
string baseUrl = "file:///c:/myimages/folder/";
This is then added to the Head of your HTML code:
string baseUrl = "file:///" + GetApplicationPath().Replace("\\", "/") + "/";
string html = "<html><head>\r\n<base href=\"" + baseUrl + "\">\r\n</head>\r\n<body><img src=\"koko.jpg\"></body></html>";
The result is the images showing up.

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert