How do you open a local html file in a web browser when the path contains an url fragment

巧了我就是萌 提交于 2020-01-23 12:53:02

问题


I am trying to open a web browser via the following methods. However, when the browser opens the url / file path, the fragment piece gets mangled (from "#anchorName" to "%23anchorName") which does not seem to get processed. So basically, the file opens but does not jump to the appropriate location in the document. Does anyone know how to open the file and have the fragment processed? Any help on this would be greatly appreciated.

an example path to open would be "c:\MyFile.Html#middle"

    // calls out to the registry to get the default browser
    private static string GetDefaultBrowserPath()
    {
       string key = @"HTTP\shell\open\command";
       using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
       {
          return ((string)registrykey.GetValue(null, null)).Split('"')[1];
       }
    }

    // creates a process and passes the url as an argument to the process
    private static void Navigate(string url)
    {
       Process p = new Process();
       p.StartInfo.FileName = GetDefaultBrowserPath();
       p.StartInfo.Arguments = url;
       p.Start();
    }

回答1:


Thanks to all that tried to help me with this issue. I have since found a solution that works. I have posted it below. All you need to do is call navigate with a local file path containing a fragment. Cheers!

    private static string GetDefaultBrowserPath()
    {
       string key = @"HTTP\shell\open\command";
       using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))
       {
          return ((string)registrykey.GetValue(null, null)).Split('"')[1];
       }
    }

    private static void Navigate(string url)
    {
       Process.Start(GetDefaultBrowserPath(), "file:///{0}".FormatWith(url));
    }



回答2:


All you need is:

System.Diagnostics.Process.Start(url);



回答3:


I am not a C# programmer, but in PHP I would do a urlencode. When I did a Google search on C# and urlencode it gave this page here at StackOverflow... url encoding using C#




回答4:


Try relying on the system to resolve things correctly:

    static void Main(string[] args)
    {
        Process p = new Process();
        p.StartInfo.UseShellExecute = true;
        p.StartInfo.FileName = "http://stackoverflow.com/questions/tagged/c%23?sort=newest&pagesize=50";
        p.StartInfo.Verb = "Open";
        p.Start();
    }


来源:https://stackoverflow.com/questions/7197967/how-do-you-open-a-local-html-file-in-a-web-browser-when-the-path-contains-an-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!