c# - 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?
解决方案
您可以让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
推荐阅读
- arm - 在简单的加法任务中使用 ARM NEON 速度较慢
- html - 在可滚动的 tbody 中对齐单元格文本
- reactjs - React 无法在 IE11 和更旧的 Android 浏览器上运行
- android - setContentView 上的 NullPointerException
- html - 使用 flex 布局时 Chrome 滚动条损坏
- python - ModuleNotFoundError:没有名为“版本”的模块
- javascript - 如何在 nativescript javascript 中从远程 php 检索多个数据?
- node.js - 无法运行节点 server.js
- typeerror - solve_ivp 错误:“所需的步长小于数字之间的间距。”
- android - 对于在线安卓游戏,有哪些服务可以保证APK文件的完整性,防止作弊?