使用Process.Start打开URL时,遇到异常?

27

我正在尝试使用Google和MSDN上都有的简单方法打开一个URL。但由于未知原因,我收到了以下异常:

Win32Exception was unhandled

Message: Application not found

异常

这是我的代码:

private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    ProcessStartInfo sInfo = new ProcessStartInfo("http://github.com/tbergeron/todoTxt");
    Process.Start(sInfo);
}
任何想法为什么它失败了? 非常感谢!

使用Firefox作为默认浏览器可能会导致此类错误。以下是启动默认浏览器的URL的编程示例:http://devtoolshed.com/content/launch-url-default-browser-using-c - wiero
我有这个想法,但我不想强制任何用户使用任何浏览器。 - Tommy B.
2
你能提供Win32Exception的错误代码吗?你可以在Win32Exception类中找到一个叫做ErrorCode和NativeErrorCode的属性。 - Hans
你成功地干净地解决了这个问题吗? - puneet
4个回答

83

我在尝试使用.NET Core时遇到了类似的问题,收到了Win32Exception的错误提示,我按照以下方式处理:

var ps = new ProcessStartInfo("http://myurl")
{ 
    UseShellExecute = true, 
    Verb = "open" 
};
Process.Start(ps);

3
非常感谢,其他方法在 .NET Core 3 中都无法奏效。 - user2577163
9
默认情况下,在.NET Framework中,UseShellExecute属性设置为true,而在.NET Core中设置为false。我猜这是异常的原因。 - Pavel Anikhouski
4
对我来说,“打开”的动词并不是必需的,可以正常工作。 - Kino101
5
在 .Net6.0 上表现良好。 - Usama Aziz

10

这显然是机器特定的行为 (http://devtoolshed.com/content/launch-url-default-browser-using-c)。

该链接文章建议使用Process.Start("http://myurl"),但捕获Win32Exception并回退到Process.Start("IExplore.exe", "http://myurl")

try
{
  Process.Start("http://myurl");
}
catch (Win32Exception)
{
  Process.Start("IExplore.exe", "http://myurl");
}

遗憾的是,尽管我尝试了几乎所有可能的方法,但这是我在我的机器上能做到的最好。


你应该使用 catch( Win32Exception w32Ex ) when ( w32Ex.NativeErrorCode == 0x800401F5 /* CO_E_APPNOTFOUND */ )。请参见我的答案:https://dev59.com/ErDla4cB1Zd3GeqP_adT#63751559。 - Dai

1
你正在寻找关于 Process.Start()string 重载版本:
Process.Start("http://github.com/tbergeron/todoTxt");

1
你确定吗?我可以重现你的异常,但使用字符串版本调用可以正常工作。你的机器可能配置不正确。 - David Heffernan

-1

如果你想在默认浏览器中启动它,请在前面加上“start”:

new ProcessStartInfo("start http://github.com/tbergeron/todoTxt");

这应该启动默认浏览器。我不想强迫任何人使用iexplore LOL。 - Tommy B.
@Tom。好观点。实际上,我一时也不知道如何启动默认浏览器。 - John Buchanan

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