WPF中正常运行的Process.Start在WinUI 3中报错,如何修复?
WinUI 3中启动默认浏览器打开URI的解决方案
在WPF中可正常运行的System.Diagnostics.Process.Start(authorizationRequest)代码,在WinUI 3中会抛出如下异常:
An error occurred trying to start process [完整的authorizationRequest字符串...] with working directory 'C:\Windows\system32'. The system cannot find the file specified.
即使已确保应用以x64架构运行,问题仍会存在,可根据应用是否打包选择对应解决方案:
1. 未打包的WinUI 3应用
修改Process.Start的调用方式,显式使用ProcessStartInfo并启用Shell执行:
// 替换原有的Process.Start(authorizationRequest)代码 var startInfo = new System.Diagnostics.ProcessStartInfo(authorizationRequest) { UseShellExecute = true }; System.Diagnostics.Process.Start(startInfo);
WinUI 3未打包应用中,直接传字符串调用Process.Start时,默认不会以Shell执行方式识别URI,显式设置UseShellExecute = true可让系统调用默认浏览器处理该URI。
2. 打包的WinUI 3应用(MSIX)
MSIX打包应用受沙箱限制,无法使用Process.Start直接打开URI,需改用Windows Runtime的Launcher类:
首先添加命名空间:
using Windows.System;
然后替换原调用代码:
// 将请求字符串转换为Uri对象 var requestUri = new Uri(authorizationRequest); // 启动默认浏览器打开URI await Launcher.LaunchUriAsync(requestUri);
Windows.System.Launcher是专为WinUI 3打包应用设计的API,可安全绕过沙箱限制启动默认应用。
额外验证步骤
可先检查URI格式是否有效,避免因格式错误导致的问题:
if (Uri.TryCreate(authorizationRequest, UriKind.Absolute, out var validUri)) { await Launcher.LaunchUriAsync(validUri); } else { // 处理无效URI逻辑 }
内容的提问来源于stack exchange,提问作者tinmac
相关产品推荐
相关产品推荐

