CScript 在 c# 中作为进程调用时仅打开 32 位版本

CScript when called as a process in c# only opens 32 bit version

我是运行一个VBS文件,需要在64位版本的cscript上执行。在命令行上,当我调用 cscript 时,它会打开位于 C:\Windows\System32\cscript.exe 的 64 位版本并且 VBS 文件工作正常。

但是,我想通过 C# 调用此 VBS 文件作为进程。使用 FileName as cscript 启动进程确实会打开 cscript,但只会打开位于 C:\Windows\SysWoW64\cscript.exe.

的 32 位版本

即使我将 FileName 设置为专门指向 64 位版本的 cscript,它也只会加载 32 位版本。

如何强制进程打开 64 位版本的 cscript?

下面是我的代码,包括上面解释的64位版本文件路径:

string location = @"C:\location";
Process process = new Process();
process.StartInfo.FileName = @"C:\Windows\System32\cscript.exe";
process.StartInfo.WorkingDirectory = location+@"\VBS\";
process.StartInfo.Arguments = "scriptName.vbs";
process.Start();

出现了一个简单的答案:

在我正在创建的 C# 应用程序中,在 Visual Studio (2017) 中选择了我的 Platform targetPrefer 32-bit,也许最好将其称为 "force 32-bit"。

通过取消选择此选项,我的进程 运行 为 64 位,既通过指定 64 位路径作为上面的代码,也通过名称 运行 cscript。

process.StartInfo.FileName = "cscript";

在“属性”>“构建”>“首选 32 位”中切换此选项

根据您的要求,还有另一种解决方案。

一些背景:当您 运行 一个 64 位应用程序并尝试启动 cscript.exe 然后您调用 C:\Windows\System32\cscript.exe(或更一般的 %windir%\System32\cscript.exe

但是,当您 运行 一个 32 位应用程序时,对 %windir%\System32\ 的每次调用都会自动重定向到 %windir%\SysWOW64\。在此目录中,您将找到所有 32 位 DLL。此重定向由 Windows 内部完成,您的应用程序无法识别任何差异。

为了从 32 位应用程序访问 %windir%\System32\,您可以使用 %windir%\Sysnative\,即即使您将应用程序编译为 32 位,process.StartInfo.FileName = @"C:\Windows\Sysnative\cscript.exe"; 也应该可以工作。

注意,文件夹 %windir%\Sysnative\ 在 64 位环境中不存在,因此您可以通过 Environment.Is64BitProcess 检查您的 运行 环境,所以

if Environment.Is64BitProcess {
   process.StartInfo.FileName = @"C:\Windows\System32\cscript.exe";
} else {
   process.StartInfo.FileName = @"C:\Windows\Sysnative\cscript.exe";
}

另见 File System Redirector

请注意,注册表也存在类似的机制,请参阅 Registry Redirector