Skip to content

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 →
  1. XamlSharp permalink
    September 26, 2016 12:34 am

    Very useful information. Thanks Brock.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: