C# - 如何在Windows 64位上获取程序文件(x86)

Leo*_*tin 151 c# windows 64-bit file

我正在使用:

FileInfo(
    System.Environment.GetFolderPath(
        System.Environment.SpecialFolder.ProgramFiles) 
    + @"\MyInstalledApp"
Run Code Online (Sandbox Code Playgroud)

为了确定是否在用户机器上检测到程序(这不是理想的,但我正在寻找的程序是MS-DOS应用程序的正确旧程序,我想不出另一种方法).

在Windows XP和32位版本的Windows Vista上,这可以正常工作.但是,在x64 Windows Vista上,代码返回x64 Program Files文件夹,而应用程序安装在Program Files x86中.有没有办法以编程方式返回程序文件x86的路径,而无需硬连线"C:\ Program Files(x86)"?

Jar*_*Par 229

以下函数将返回Program Files所有这三种Windows配置中的x86 目录:

  • 32位Windows
  • 在64位Windows上运行的32位程序
  • 64位程序在64位窗口上运行

 

static string ProgramFilesx86()
{
    if( 8 == IntPtr.Size 
        || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
    {
        return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
    }

    return Environment.GetEnvironmentVariable("ProgramFiles");
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不只是`Environment.Is64BitOperatingSystem`或`Environment.Is64BitProcess`? (10认同)
  • @anustart在.NET 4.0中提供这些方法之前,这在2008年得到了回答. (7认同)
  • @Tom它适用于pt-BR Win 7 Ultimate x64 (2认同)

Nat*_*han 132

如果您使用的是.NET 4,则会有一个特殊的文件夹枚举ProgramFilesX86:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Run Code Online (Sandbox Code Playgroud)

  • Microsoft的文档声明:"在x86系统上,将ProgramFilesX86成员传递给Environment.GetFolderPath方法返回String.Empty;改为使用ProgramFiles成员.您可以通过调用Environment.Is64BitOperatingSystem属性来确定Windows是否是32位操作系统". (12认同)
  • 是.它将在x86上返回c:\ program files,在64位窗口上返回c:\ program files(x86). (6认同)
  • 在Windows XP上也返回空字符串(32位) (4认同)
  • 在32位OS上该如何表现?它是否在没有x86的情况下返回“ c:\ Program files”? (2认同)
  • 自己测试 - 在Server 2003 32位上,这为我返回空字符串:Console.WriteLine("X86:"+ System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86)); (2认同)

Car*_*erg 42

Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
Run Code Online (Sandbox Code Playgroud)


cha*_*ers 14

但请注意,ProgramFiles(x86)只有在应用程序运行64位时,环境变量才可用.

如果您的应用程序运行32位,您可以使用ProgramFiles其值实际上为"Program Files(x86)" 的环境变量.


tom*_*asr 9

一种方法是查找"ProgramFiles(x86)"环境变量:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
Run Code Online (Sandbox Code Playgroud)


小智 5

我正在编写一个可以在Windows 7的x86和x64平台上运行的应用程序,并查询下面的变量只需在任何平台上拉出正确的程序文件文件夹路径.

Environment.GetEnvironmentVariable("PROGRAMFILES")
Run Code Online (Sandbox Code Playgroud)