.Net Core 2.0 Process.Start 抛出 "The specified executable is not a valid application for this OS platform"

.Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform"

我需要让 .reg 文件和 .msi 文件使用与用户 Windows.

关联的这两种文件类型的任何可执行文件自动执行

.NET Core 2.0 Process.Start(string fileName) docs 说: "the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system."

但是

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 版本)并且不受我的控制。这也是为什么我需要将程序移植到 .Net Core,试图让它作为 SCD 控制台应用程序工作,这样就不需要安装特定的 .Net Framework 或 .NET Core 版本。

在 Visual Studio 调试 运行 和发布为 win-x86 SCD 时都会抛出异常。我的 PC 是 Win7 64 位,我确定 .reg 和 .msi 与往常一样与常规程序相关联 Windows PC。

有解决办法吗?感谢任何帮助。

你必须执行cmd.exe

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

别忘了 /c

您还可以将ProcessStartInfoUseShellExecute 属性设置为true

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

似乎是 .net Core 中的更改,如文档所述here

另见 breaking changes

您可以将 UseShellExecute 设置为 true 并将其和您的路径包含在 ProcessStartInfo 对象中:

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

使用它打开一个文件

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

需要这个扩展方法

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

如果这也困扰您:

对于我们这些习惯于简单地调用Process.Start(fileName);的人来说,上面的语法可能会让我们感到焦虑......所以我可以补充一下,你可以在一行代码中编写它吗?

new Process { StartInfo = new ProcessStartInfo(fileName) { UseShellExecute = true } }.Start();