使用默认Web浏览器打开html文件

时间:2012-06-12 02:03:43

标签: c# browser

我正在使用它来获取默认Web浏览器的路径和可执行文件:

public static string DefaultWebBrowser
        {
            get
            {

                string path = @"\http\shell\open\command";

                using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(path))
                {
                    if (reg != null)
                    {
                        string webBrowserPath = reg.GetValue(String.Empty) as string;

                        if (!String.IsNullOrEmpty(webBrowserPath))
                        {
                            if (webBrowserPath.First() == '"')
                            {
                                return webBrowserPath.Split('"')[1];
                            }

                            return webBrowserPath.Split(' ')[0];
                        }
                    }

                    return null;
                }
            }
        }

 protected static bool Run(string FileName, string Args)
        {
            try
            {
                Process proc = new Process();

                processInfo.FileName = FileName;
                 proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

                if(Args != null) proc.StartInfo.Arguments = Args;

                proc.Start();

                return true;
            }
            catch (Exception) { }

            return false;
        }

然后我调用网络浏览器:Run(DefaultWebBrowser, "foo.html")

问题是:上面的功能是调用Firefox和IE(我的电脑上安装的两个Web浏览器)而不是Internet Explorer,即默认的Web浏览器。我不知道如何解决这个问题。

修改

我已经下载并安装了谷歌浏览器,将其设置为默认的网络浏览器,但奇怪的是上述错误不会发生。

4 个答案:

答案 0 :(得分:29)

您可以用

替换所有代码
System.Diagnostics.Process.Start(pathToHtmlFile);

这会自动启动默认浏览器,或者查找.htm.html文件的默认处理程序并使用它。

现在将Firefox设置为默认值,这有时会导致奇怪的异常(我认为如果Firefox首次启动),那么您可能需要在其上执行try/catch来处理它。

答案 1 :(得分:1)

对于那些没有与浏览器进行html默认关联的人,请使用

System.Diagnostics.Process.Start("Chrome", Uri.EscapeDataString(pathToHtmlFile))

答案 2 :(得分:1)

对于.Net Core,您需要致电(在.Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform"中建议)

 var proc = Process.Start(@"cmd.exe ", @"/c " + pathToHtmlFile); 

当我尝试Process.Start(pathToHtmlFile);时, 我有 System.ComponentModel.Win32Exception:指定的可执行文件不是此OS平台的有效应用程序。

答案 3 :(得分:0)

我正在使用代码,我首先查找exe文件。 例如,如果exsists chrome.exe(在其默认路径中),否则如果存在firefox.exe或launcher.exe(用于opera)等...如果不存在,请尝试使用pathToHtmlFile参数运行iexplore.exe。这是我的解决方案,我使用外部配置,其中设置我的浏览器,无论操作系统中默认设置是什么。