DEV Community

artydev
artydev

Posted on

.Net Core - Launch Browser when application start

You want to distribute a .Net Core App and don't want user to have to launch a browser manually.

In your publish settings choose :

  • standalone
  • single file application

In your program.cs put the following code :

an adaptation of the following post LaunchBrowser

  using Microsoft.AspNetCore;
  using Microsoft.AspNetCore.Hosting;
  using System.Diagnostics;
  using Microsoft.AspNetCore.Builder;
  using static System.Runtime.InteropServices.RuntimeInformation;
  using static System.Runtime.InteropServices.OSPlatform;
  using Microsoft.Extensions.Hosting;

  class Program
  {
    static void Main(string[] args)
    {
      string url = "http://localhost:54321/";

      using (var server = CreateServer(args, url))
      {
        StartBrowserWhenServerStarts(server, url);
        server.Run(); //blocks
      }
    }

    /// <summary>
    /// Create the kestrel server, but don't start it
    /// </summary>
    private static IWebHost CreateServer(string[] args, string url) => WebHost
        .CreateDefaultBuilder(args)
        .UseStartup<YourAppName.Startup>()
        .UseUrls(url)
        .Build();

    /// <summary>
    /// Register a browser to launch when the server is listening
    /// </summary>
    private static void StartBrowserWhenServerStarts(IWebHost server, string url)
    {
      IHostApplicationLifetime serverLifetime = (IHostApplicationLifetime)server.Services.GetService(typeof(IHostApplicationLifetime));
      serverLifetime.ApplicationStarted.Register(() =>
      {
        var browser =
            IsOSPlatform(Windows) 
              ? new ProcessStartInfo("cmd", $"/c start {url}") 
              : IsOSPlatform(OSX) 
                ? new ProcessStartInfo("open", url) 
                : new ProcessStartInfo("xdg-open", url); //linux, unix-like

        Process.Start(browser);
      });
    }
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)