Process.Start for URLs on .NET Core
September 24, 2016
Apparently .NET Core is sort of broken when it comes to opening a URL via Process.Start. Normally you’d expect to do this:
Process.Start("http://google.com")
And then the default system browser pops open and you’re good to go. But this open issue explains that this doesn’t work on .NET Core. So instead you have to do this (credit goes to Eric Mellino):
public static void OpenBrowser(string url) { try { Process.Start(url); } catch { // hack because of this: https://github.com/dotnet/corefx/issues/10361 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Process.Start("xdg-open", url); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Process.Start("open", url); } else { throw; } } }
I added a few more fixes for Windows — one was suppressing the second command prompt, and another was escaping the “&” with “^&” so the shell does not treat them as command separators.
Fun times in this cross-platform world.
One Comment
leave one →
Very useful information. Thanks Brock.