tags:

views:

131

answers:

2

I have a situation where I need to return a directory path by reading the registry settings. Registry value returns me a path in the format

%CommonProgramFiles%\System\web32.dll

while the consumer code is expecting it in the format

C:\Program Files\Common Files\System\web32.dll

How can I resolve such directory path in .net code?

+4  A: 

Environment.ExpandEnvironmentVariables. If you control the creation of the registry value, store it as an expandable string in the registry and the registry API will automatically expand it for you.

Marcelo Cantos
I need a full directory path and it could be any other environment variable, not just %CommonProgramFiles%
Faisal
I don't understand your comment, @Faisal. `ExpandEnvironmentVariables` will expand any environment variable it sees in the string you supply, and will yield a full path in the specific case you cite in the question.
Marcelo Cantos
ok that worked. Thanks
Faisal
+1  A: 

You can use the Environment.GetEnvironmentVariable function:

string commonDir = Environment.GetEnvironmentVariable("CommonProgramFiles");

You can then use Path.Combine to append the rest of the path:

string fullPath = Path.Combine(commonDir, "System", "web32.dll");

Another option is to use Environment.ExpandEnvironmentVariables. This will replace all environment variables with their values:

string fullPath = Environment.ExpandEnvironmentVariables("%CommonProgramFiles%\System\web32.dll");
Oded
Of course, that override of `Path.Combine` only works in v4 of the framework
Rowland Shaw