How do I reference a local resource in generated HTML in WinForms WebBrowser control?

前端 未结 5 681
天涯浪人
天涯浪人 2020-12-18 11:32

I\'m using a winforms webbrowser control to display some content in a windows forms app. I\'m using the DocumentText property to write the generated HTML. That part is wor

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 12:28

    Ken's code was missing a few things that it needed to work. I've revised it, and created a new method that should automate things a little.

    Just call the static method as so:

    html = HtmlFormatter.ReplaceImagePathAuto(html);
    

    and all links in the html that match file://ApplicationPath/ will be swapped with the current working directory. If you want to specify an alternate location, the original static method is included (plus the bits it was missing).

    public class HtmlFormatter
    {
    
        public static readonly string FILE_URL_PREFIX = "file://";
        public static readonly string PATH_SEPARATOR = "/";
        public static String ReplaceImagePath(String html, String path)
        {
            return html.Replace("file://ApplicationPath/", path);
        }
        /// 
        /// Replaces URLs matching file://ApplicationPath/... with Executable Path
        /// 
        /// 
        /// 
        public static String ReplaceImagePathAuto(String html)
        {
            String executableName = System.Windows.Forms.Application.ExecutablePath;
            System.IO.FileInfo executableFileInfo = new System.IO.FileInfo(executableName);
            String executableDirectoryName = executableFileInfo.DirectoryName;
            String replaceWith = HtmlFormatter.FILE_URL_PREFIX
                + executableDirectoryName
                + HtmlFormatter.PATH_SEPARATOR;
    
            return ReplaceImagePath(html, replaceWith);
        }
    }
    

提交回复
热议问题