Process.Start 报错

发布时间 2023-08-14 12:49:11作者: 龙骑科技

Process.Start 报错 System.Diagnostics.Process.StartWithShellExecuteEx

Process.Start 为什么会引发“系统找不到指定的文件”异常

Process.Start 报错 找不到路径 ,System.ComponentModel.Win32Exception:“系统找不到指定的文件。

问题1

在WinForm中可能是权限问题,设置文件夹和文件权限即可,也可能是NET版本太低了,只要把项目版本从net2.0  换成4.0以及以上,同时 解决方案平台设置位 AnyCPU 即可

//报错找不到路径 ,System.ComponentModel.Win32Exception:“系统找不到指定的文件。” ----只要把net2.0 换成4.0以及以上,同时 解决方案平台设置位 AnyCPU 即可
//Process.Start(@"F:\osk.exe");
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "osk.exe");
Process.Start(path);
   var p = new Process();
            p.StartInfo = new ProcessStartInfo(path)
            {
                WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System),
                UseShellExecute = true,
                Verb = "runas" //管理员权限
            };
            p.Start();

 

问题2

在NET6 中可能是NET Framework 版本的最后执行的是StartWithShellExecuteEx而不是StartWithCreateProcess方法

造成这样的原因,是因为UseShellExecute在 .NET 6 上默认为 false:

public bool UseShellExecute { get; set; }

而在 .NET Framework 上默认为 true:

//
// 摘要:
// Gets or sets a value indicating whether to use the operating system shell to
// start the process.
//
// 返回结果:
// true if the shell should be used when starting the process; false if the process
// should be created directly from the executable file. The default is true.
[DefaultValue(true)]
[MonitoringDescription("ProcessUseShellExecute")]
[NotifyParentProperty(true)]
public bool UseShellExecute { get; set; }

问题3、

如果想使用参数的话,需要在 Arguments上设置参数

 var p = new Process();
            p.StartInfo = new ProcessStartInfo(path)
            {
                WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System),
                UseShellExecute = true,
                Verb = "runas",
                Arguments="参数"
            };
            p.Start();