【问题标题】:How do you open a local html file in a web browser when the path contains an url fragment当路径包含 url 片段时,如何在 Web 浏览器中打开本地 html 文件
【发布时间】:2011-11-04 02:34:00
【问题描述】:

我正在尝试通过以下方法打开网络浏览器。但是,当浏览器打开 url / 文件路径时,片段片段会被损坏(从“#anchorName”到“%23anchorName”),这似乎没有得到处理。所以基本上,文件打开但不会跳转到文档中的适当位置。有谁知道如何打开文件并处理片段?对此的任何帮助将不胜感激。

打开的示例路径是“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();
    }

【问题讨论】:

  • 也许尝试在 URL 前添加 file:///
  • 谢谢,我试过我发布的这个 b/f。它不起作用。

标签: c# fragment process.start


【解决方案1】:

感谢所有试图帮助我解决这个问题的人。从那以后,我找到了一个可行的解决方案。我已经在下面发布了。您需要做的就是使用包含片段的本地文件路径调用导航。干杯!

    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】:

    你只需要:

    System.Diagnostics.Process.Start(url);
    

    【讨论】:

    • 我在发布之前尝试过此操作,但由于片段而引发了文件未找到异常。
    • @user248450:尝试引用 URL。无论如何,+1。
    • 在这个过程中,它启动了进程,但文件没有出现在浏览器中。
    • @GaneshKumar 你可以查看this link
    • @arviman 这个错误是怎么回事“系统找不到指定的文件”
    【解决方案3】:

    尝试依靠系统正确解决问题:

        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();
        }
    

    【讨论】:

    • 感谢 phillip 提供的信息,但您在此处提供的示例是指向外部网站的链接。我正在我的硬盘驱动器上打开一个不使用相同进程的文件。当它是一个本地文件时,该进程查看注册表以确定使用哪个默认程序打开具有给定扩展名的文件。因为您的示例是外部网页,Windows 可以确定它处理的是一个 url 并适当地处理它。上面,通过查找用户首选程序来强制执行其中一些,因为当有片段时,Windows 无法破译扩展名
    • 我只是尝试了这个很好的措施,片段被使用 @"C:\Test.html#middle" 剥离结果 "file:///C:/Test.html" 再次感谢你的建议。
    • 它实际上使应用程序因找不到文件异常而崩溃。我第一次尝试没有片段。哎呀。
    【解决方案4】:

    我不是 C# 程序员,但在 PHP 中我会做一个 urlencode。当我在 C# 和 urlencode 上进行谷歌搜索时,它在 StackOverflow 上给出了这个页面...url encoding using C#

    【讨论】:

    • 这没有任何意义,已经是一个URL,他没有在这段代码中附加参数......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2016-04-20
    • 1970-01-01
    • 2014-04-27
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多