【问题标题】:Open data URI from c# in default browser在默认浏览器中从 c# 打开数据 URI
【发布时间】:2014-03-07 14:12:04
【问题描述】:

我有一个字符串,它是一个数据 URI。例如

string dataURI = data:text/html,<html><p>This is a test</p></html>

然后我通过使用调用网络浏览器

System.Diagnostics.Process.Start(dataURI)

但是网络浏览器没有打开,我只是得到一个错误。当我将数据 URI 粘贴到浏览器地址栏中时,它会很好地打开页面。

谁能帮助我并告诉我我做错了什么?

谢谢你,托尼

【问题讨论】:

  • 你遇到了什么错误?
  • 它是德语的 :( 我翻译成这样:运行失败。目标导致异常。

标签: c# browser uri


【解决方案1】:

据此article

ShellExecute 解析传递给它的字符串,以便 ShellExecute 可以提取协议说明符或扩展名。接下来,ShellExecute 查看注册表,然后使用协议说明符或扩展名来确定启动哪个应用程序。如果您将 http://www.microsoft.com 传递给 ShellExecute,ShellExecute 会将 http:// 子字符串识别为协议。

在您的情况下,没有 http 子字符串。因此,您必须将默认浏览器可执行文件作为文件名和数据 URI 作为参数显式传递。我使用了article 中的GetBrowserPath 代码。

string dataURI = "data:text/html,<html><p>This is a test</p></html>";
string browser = GetBrowserPath();
if(string.IsNullOrEmpty(browser))
    browser = "iexplore.exe";
System.Diagnostics.Process p = new Process();
p.StartInfo.FileName = browser;
p.StartInfo.Arguments = dataURI;
p.Start();

private string GetBrowserPath()
{
    string browser = string.Empty;
    Microsoft.Win32.RegistryKey key = null;
    try
    {
        // try location of default browser path in XP
        key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);
        // try location of default browser path in Vista
        if (key == null)
        {
            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
        }
        if (key != null)
        {
            //trim off quotes
            browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
            if (!browser.EndsWith("exe"))
            {
                //get rid of everything after the ".exe"
                browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
            }                    
        }
    }
    finally
    {
        if (key != null) key.Close();
    }
    return browser;
}

【讨论】:

  • 我试过你的方法,但不知何故没用。它正确调用了浏览器,但只传递了 URI 的一部分。无论如何,现在我创建了一个临时文件并让浏览器显示它而不是数据 URI,它可以完美运行。但感谢您的帮助,这让我明白了问题所在。
猜你喜欢
  • 2011-06-02
  • 2011-05-09
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
相关资源
最近更新 更多