首页 > 解决方案 > Process.Start() 打开 URL 有时会抛出 Win32Exception?

问题描述

我有以下代码在默认浏览器中打开 URL:

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

但它会失败并抛出Win32Exception一些 URL,例如:

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%

堆栈跟踪如下:

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)

我一直在将默认浏览器从 firefox 切换到 chrome、edge、brave 等。

我在这个 dotnet 问题中尝试了一些解决方法,

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

或者

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

但仍然没有运气,无法打开我的默认浏览器。错误信息还在The system cannot find the file specified.

有一些解决方案可以打开 Internet Explorer,但它们不符合我的规范。

如何在任何默认浏览器中打开这样的 url?

标签: c#windowsbrowserprocesssystem.diagnostics

解决方案


您可以让UriBuilder类为您完成解码工作。

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());

其实只是对原来的字符串稍加修改,增加了服务端口,但足以让字符串成为可识别的URL。

如果您尝试使用WebUtility类 对其进行解码,它将无法正常工作:

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

推荐阅读