How do I programmatically retrieve the actual path to the “Program Files” folder? [duplicate]

霸气de小男生 提交于 2019-12-03 08:32:28

问题


Possible Duplicate:
C# - How to get Program Files (x86) on Windows Vista 64 bit

I realize the odds of a user changing the Windows default of C:\Program Files is fairly slim, but stranger things have happened!

How can I get the correct path to Program Files from the system?


回答1:


.NET provides an enumeration of 'special folders' for Program Files, My Documents, etc.

The code to convert from the enumeration to the actual path looks like this:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

http://msdn.microsoft.com/en-us/library/14tx8hby.aspx




回答2:


Just to add to this.

If you're running in 32 bit mode (even on a 64 bit os), SpecialFolder.ProgramFiles and %PROGRAMFILES% will return ..Program Files (x86).

If you specifically need one and/or the other then you'll need to check as follows:

32 bit system:

SpecialFolder.ProgramFiles = ..Program Files\

64 bit system in 32 bit process: SpecialFolder.ProgramFiles = ..Program Files (x86)\ Environment.GetEnvironmentVariable("ProgramW6432") = ..Program Files\

64 bit system in 64 bit process: SpecialFolder.ProgramFiles = ..Program Files\ Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") = ..Program Files (x86)\

Obviously this depends on your locale etc...




回答3:


You would use GetFolderPath in the Environment class.

try {
    Environment.GetFolderPath( Environment.SpecialFolder.ProgramFiles )
catch( ArgumentException ex ) {
    Console.Out.WriteLine( ex.StackTrace );
}



回答4:


Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) is probably the best solution, but another possible variant is evaluating the value of the ProgramFiles environment variable. For this, you can use the GetEnvironmentVariable or ExpandEnvironmentVariables method of the Environment class:

Environment.GetEnvironmentVariable("ProgramFiles")

Environment.ExpandEnvironmentVariables("%ProgramFiles%")



回答5:


You can access the environment variable called: %PROGRAMFILES%

i.e:

%PROGRAMFILES%\Maxis\SimCity

in C#:

System.Environment.SpecialFolder.ProgramFiles



回答6:


Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

gets "program files (x86)" in 64-bits Windows and "program files" in 32 bit.



来源:https://stackoverflow.com/questions/1085584/how-do-i-programmatically-retrieve-the-actual-path-to-the-program-files-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!