17

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?

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
Tabai smida
  • 171
  • 1
  • 4

4 Answers4

24

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

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
5

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

JaggenSWE
  • 1,950
  • 2
  • 24
  • 41
  • 4
    This is a "trick". It is better to use `Environment.SpecialFolder`. – i486 Nov 23 '15 at 09:37
  • How come it's a "trick"? It's calling an environment variable and will return the value the OP is after. Using the specialfolder doesn't seem to work for him. – JaggenSWE Nov 23 '15 at 09:41
  • Of course, this only works on 64 bit systems that still have WOW64. Pure 64 bit systems will by necessity run your program in 64 bits mode even if marked "Any CPU, prefer 32 bits" (i.e. Server Core). – MSalters Nov 23 '15 at 13:32
1

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

Community
  • 1
  • 1
Nisha Salim
  • 687
  • 5
  • 13
0

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)

Community
  • 1
  • 1
Clint
  • 6,011
  • 1
  • 21
  • 28