Search code examples
c#windowsbrowserprocesssystem.diagnostics

Process.Start() open URL throws Win32Exception sometimes?


I have the following code to open a URL in default browser:

string url;
//...
Process.Start(url);

But it will fail and throws a Win32Exception with some URL, for example:

https://tw.news.yahoo.com/%E6%95%B8%E4%BD%8D%E8%BA%AB%E5%88%86%E8%AD%89%E6%93%AC9%E6%9C%88%E6%8F%90%E6%A8%A3%E5%BC%B5-%E5%BE%90%

The stack trace is like:

System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified.
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start(String fileName)
   at MyApp.GoURL(String url)

I have been switching deafult browsers from firefox to chrome, edge, brave, ... etc.

And I tried some workarounds in this dotnet issue,

Process.Start(
    new ProcessStartInfo("cmd", $"/c start {url}") 
    { CreateNoWindow = true });

or

ProcessStartInfo psi = new ProcessStartInfo
{
    FileName = url,
    UseShellExecute = true
};
Process.Start(psi);

but still no luck, cannot open my default browser. The error message is still The system cannot find the file specified.

There are some solutions opening internet explorer, but they do not fit my spec.

How could I open such url in any default browser?


Solution

  • You could let the UriBuilder class do the decoding work for you.

    string urlEncoded = @"https://tw.news.yahoo.com/%E6%95%B8%E4%BD%8D%E8%BA%AB%E5%88%86%E8%AD%89%E6%93%AC9%E6%9C%88%E6%8F%90%E6%A8%A3%E5%BC%B5-%E5%BE%90%";
    
    var builder = new UriBuilder(urlEncoded);
    Process.Start(builder.ToString());
    

    It's actually just a small modification to the original string, adding the service port, but it's enough for the string to become a recognized URL.

    It won't work if you try to decode it, using the WebUtility class:

     string urlDecoded = WebUtility.UrlDecode(urlEncoded);
     Process.Start(urlDecoded);  // Fail