OITA: Oika's Information Technological Activities

@oika 情報技術的活動日誌。

.NET Core Process.Start(URL) でWEBブラウザを表示できない

.NET Frameworkでは、Process.Start("https://www.google.co.jp/")とかやると、既定のブラウザが勝手に開いてGoogleのページを開いてくれたもんなんですが、.NET Coreではそれはできなくなったっぽい。

System.ComponentModel.Win32Exception: 指定されたファイルが見つかりません。  
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)  
   at System.Diagnostics.Process.Start()  
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)  

プラットフォームに依存するような動作はやめますってことなのかな。

で、すでに対策を考えてくれていた方がいました。

Process.Start for URLs on .NET Core

//string url  

try  
{  
    Process.Start(url);  
}  
catch  
{  
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))  
    {  
        //Windowsのとき  
        url = url.Replace("&", "^&");  
        Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });  
    }  
    else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))  
    {  
        //Linuxのとき  
        Process.Start("xdg-open", url);  
    }  
    else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))  
    {  
        //Macのとき  
        Process.Start("open", url);  
    }  
    else  
    {  
        throw;  
    }  
}  

とりあえずWindows環境では動くことを確認。
& をエスケープしてるのは、シェルがそこをコマンドの切れ目と認識しちゃうかららしい。