. Net Core 2.0 Process. Start 抛出“指定的可执行文件不是此操作系统平台的有效应用程序”

我需要让一个。注册文件和一个。Msi 文件使用与用户 Windows 上的这两种文件类型相关联的任何可执行文件自动执行。

NET Core 2.0 Process. Start (string fileName) docs 说: ”文件名不需要表示可执行文件。它可以是任何文件类型,扩展名与系统上安装的应用程序相关联。”

然而

using(var proc = Process.Start(@"C:\Users\user2\Desktop\XXXX.reg")) { } //.msi also

给了我

System.ComponentModel.Win32Exception (0x80004005): The specified executable is not a valid application for this OS platform.
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(String fileName)

使用 ErrorCode 和 HResult -2147467259以及 NativeErrorCode 193。

同样的代码在.Net Framework 3.5或4控制台应用程序中也可以工作。

我不能指定精确的 exe 文件路径作为方法的参数,因为用户的环境是不同的(包括 Windows 版本) ,并且不在我的控制范围之内。这也是为什么我需要把程序移植到。NetCore,尝试使其作为 SCD控制台应用程序工作,以便安装特定的。网络架构或。不需要 NET 核心版本。

异常在 VisualStudio 调试运行和以 win-x86SCD 发布时都会引发。我的电脑是 Win764位,我确定。Reg 和 Reg。Msi 和通常的 Windows PC 一样与常规程序相关联。

有什么解决办法吗? 感谢您的帮助。

58538 次浏览

You have to execute cmd.exe

var proc = Process.Start(@"cmd.exe ",@"/c C:\Users\user2\Desktop\XXXX.reg")

don't forget the /c

You can also set the UseShellExecute property of ProcessStartInfo to true

var p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Users\user2\Desktop\XXXX.reg")
{
UseShellExecute = true
};
p.Start();

Seems to be a change in .net Core, as documented here.

See also breaking changes.

You can set UseShellExecute to true and include this and your path in a ProcessStartInfo object:

Process.Start(new ProcessStartInfo(@"C:\Users\user2\Desktop\XXXX.reg") { UseShellExecute = true });

use this to open a file

new ProcessStartInfo(@"C:\Temp\1.txt").StartProcess();

need this extension method

public static class UT
{
public static Process StartProcess(this ProcessStartInfo psi, bool useShellExecute = true)
{
psi.UseShellExecute = useShellExecute;
return Process.Start(psi);
}
}

In case this bothers you as well:

For those of us that are used to simply calling Process.Start(fileName); the above syntax may give us anxiety... So may I add that you can write it in a single line of code?

new Process { StartInfo = new ProcessStartInfo(fileName) { UseShellExecute = true } }.Start();
            string itemseleccionado = lbdatos.SelectedItem.ToString();
var p = new Process();
p.StartInfo = new ProcessStartInfo(itemseleccionado)
{
UseShellExecute = true
};
p.Start();