2014-03-07 58 views
0

我有一个字符串,它是一个数据URI。例如在默认浏览器中从c#打开数据URI

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

然后我用

System.Diagnostics.Process.Start(dataURI) 

调用Web浏览器,但在Web浏览器不开,我刚刚得到一个错误。当我将我的数据URI粘贴到浏览器地址栏中时,它会很好地打开页面。

任何人都可以请帮助我,告诉我我做错了什么?

谢谢你,托尼

+0

你会得到什么错误? – Junaith

+0

这是德文:( 我翻译了类似以下内容:运行失败。目标导致异常。 – tomet

回答

2

按本article

的ShellExecute分析传递给它,这样的ShellExecute可以提取无论是协议说明符或扩展的字符串。接下来,ShellExecute会在注册表中查找,然后使用协议说明符或扩展名来确定要启动的应用程序。如果将http://www.microsoft.com传递给ShellExecute,则ShellExecute将http://子字符串识别为协议。

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

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; 
} 
+0

我试过了你的方法,但是它不起作用。它正确调用了浏览器,但只传递了部分URI。 无论如何,现在我创建了一个临时文件,并让浏览器显示,而不是数据URI,完美地工作。但我感谢您的帮助,它让我明白了这个问题。 – tomet

相关问题