Reputation: 5279
I have weird problem.
I`m using windows 7 enterprise sp1 64 bit.
I need to take Program files and Program files X86 directories path for my project. This is what I've done:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
but both of these lines returns Program files X86 folder.
How can I resolve it?
Upvotes: 42
Views: 52844
Reputation: 14521
The result depends on what platform is your project targeting. If you target x86, then both Environment.SpecialFolder.ProgramFiles
and Environment.SpecialFolder.ProgramFilesX86
will return the same path.
For example to get the actual path as a string
use
string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
Upvotes: 34
Reputation: 6499
The approach that you have taken is absolutely correct. We just need to tell the compiler to not prefer a particular build platform
Its as simple as
Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"
Upvotes: 0
Reputation: 302
David's answer will work only for Windows 7 and above as per Dan Nolan's comment.
Here is a solution that will work for x86, x64 or Any CPU configurations AND will work for older versions of Windows.
string ProgramFiles = Environment.ExpandEnvironmentVariables("%ProgramFiles%");
if (ProgramFiles[ProgramFiles.Length-1].Equals(')')) // If ProgramFiles(x86)
ProgramFiles = ProgramFiles.Substring(0, ProgramFiles.Length - 6);
Essentially, just remove the (x86) if it is there, when it shouldn't be.
OR:
Looking at this registry value seems like a reliable solution too: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir
Upvotes: 0
Reputation: 961
This will work for x86, x64 or Any CPU configurations:
string programFiles = Environment.ExpandEnvironmentVariables("%ProgramW6432%");
string programFilesX86 = Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%");
Because using the environment variable ProgramW6432
will always return Program Files folder whereas ProgramFiles
will vary depending on your application compilation options.
Upvotes: 86
Reputation: 31077
Use the Configuration Manager (Build -> Configuration Manager) in Visual Studio to change the targeted platform.
In the platform column see if x64 is available. If it is not, click on the drop down and select "New". You will then be able to add the x64 as a target platform. Debug again, and you will see that Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
will return C:\Program Files
.
Upvotes: 4
Reputation: 1214
Environment.SpecialFolder.ProgramFiles
should return the x86 folder for a 32-bit application and Program Files for a 64-bit application on 64-bit Windows. Check your project configuration settings.
Upvotes: 3