Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a user environment variable in C#?

Tags:

How can I read a user specific environment variable? I know how to get a system wide one, like

Environment.GetEnvironmentVariable("SOMETHING"); 

Thanks in advance!

like image 905
Deleted Avatar asked Aug 04 '10 08:08

Deleted


People also ask

How do you read environment variables?

An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.

How do I get an environment variable from a program?

To access the value of an environment variable from a COBOL program, call the getenv() function. To set environment variables for z/OS UNIX COBOL programs from a shell, use the export or set command. To set environment variables from within the program, call POSIX functions setenv() or putenv().

How do I view a variable in CMD?

Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.


2 Answers

Use the other overload of the Environment.GetEnvironmentVariable Method that lets you specify the EnvironmentVariableTarget.

Environment.GetEnvironmentVariable(variable, target); 

target can be:
EnvironmentVariableTarget.Process,
EnvironmentVariableTarget.User,
EnvironmentVariableTarget.Machine.

like image 150
Jaroslav Jandek Avatar answered Nov 22 '22 10:11

Jaroslav Jandek


It's the same method, just set the second parameter to be User as:

System.Environment.GetEnvironmentVariable("varName", EnvironmentVariableTarget.User); 
like image 36
Hans Olsson Avatar answered Nov 22 '22 12:11

Hans Olsson