当路径包含URL片段时,如何在Web浏览器中打开本地HTML文件

3
我正在尝试通过以下方法打开Web浏览器。然而,当浏览器打开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:///”? - Ry-
谢谢,我在发布之前已经尝试过了。它不起作用。 - user248450
4个回答

5

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

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

3

您所需的是:

System.Diagnostics.Process.Start(url);

在此中,它启动了进程,但文件未出现在浏览器中。 - GaneshKumar
@GaneshKumar 你可以查看这个链接 - arviman
@arviman 它显示了这个错误:“系统找不到指定的文件” - GaneshKumar
@GaneshKumar,请将路径更改为您计算机上的IExplore.exe所在位置。 - arviman
使用此方法会剥离URL的片段部分。 - Clément
显示剩余2条评论

1
尝试依赖系统来正确解决问题。
    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无法解密扩展名。 - user248450
1
我只是为了保险起见尝试了一下。使用@"C:\Test.html#middle" 后,片段被剥离,结果为 "file:///C:/Test.html"。再次感谢您的建议。 - user248450
1
它实际上会导致应用程序崩溃,并显示文件未找到异常。第一次尝试时我没有使用片段,糟糕。 - user248450

0

我不是C#程序员,但在PHP中我会使用urlencode。当我在Google上搜索C#和urlencode时,它给出了StackOverflow上的这个页面... 使用C#进行URL编码


这没有任何意义,这已经是一个URL了,在这段代码中他没有添加参数... - Ry-

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接