简体   繁体   中英

How do I get the Program Files directory?

I'm trying to get the Program Files directory in a 64-bit OS. This code below returns the same answer Program Files (x86) :

Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86).ToString());
Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).ToString());

Any help?

You must run your program in 64 bit mode of course. Then this will print

C:\Program Files (x86)
C:\Program Files 

Go to : Project > Your Project Properties... > Build > disable Prefer 32-bit

This is what you want:

Environment.GetEnvironmentVariable("ProgramW6432")

It will return the path to the x64 program directory.

For more info regarding the Environment variables and WOW64, read here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384274(v=vs.85).aspx

For this

Console.WriteLine(Environment.GetEnvironmentVariable("ProgramFiles(x86)"));

Please check this link C# - How to get Program Files (x86) on Windows 64 bit

Above link shows it'll return the x86 Program Files directory in all of these three Windows configurations:

32 bit Windows
32 bit program running on 64 bit Windows
64 bit program running on 64 bit windows

Solution:

We need to tell the compiler to not prefer a particular build platform.

Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"

Reason:

By default for most .NET Projects is "Any CPU 32-bit preferred"

When you uncheck 32 bit assembly will:

JIT to 32-bit code on 32 bit process

JIT to 32-bit code on 64 bit process

C# Code:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

Output:

C:\\Program Files (x86)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM