Environment variables

Oracle Home Selector application read and modify (and create if not exists) the following environment variables:
  • ORACLE_HOME - path to the current oracle home
  • PATH - contains path to the oracle home's bin folder
  • NLS_LANG - defines language, territory and character set properties used by the client application

Working with environment variables in .NET

Methods

For working with environment variables class System.Environment provides 3 static methods:
  • GetEnvironmentVariable
  • GetEnvironmentVariables
  • SetEnvironmentVariable

string s = Environment.GetEnvironmentVariable("NLS_LANG", EnvironmentVariableTarget.User);
Console.WriteLine(s);

EnvironmentVariableTarget

For example, we have environment variable COLOR defined both as User and as System variable:

envvar1.jpg

Using Environment.GetEnvironmentVariable with different values for EnvironmentVariableTarget will receive the following result:
string var = "COLOR";
Console.WriteLine("var:         {0}",
     Environment.GetEnvironmentVariable(var));
Console.WriteLine("Machine var: {0}",
     Environment.GetEnvironmentVariable(var, EnvironmentVariableTarget.Machine));
Console.WriteLine("Process var: {0}",
     Environment.GetEnvironmentVariable(var, EnvironmentVariableTarget.Process));
Console.WriteLine("User var:    {0}",
     Environment.GetEnvironmentVariable(var, EnvironmentVariableTarget.User));
var:         Red
Machine var: Green
Process var: Red
User var:    Red


NB
PATH variable works a little different - when GetEnvironmentVariable without EnvironmentVariableTarget parameter, then the return value will be concatenation of User and System variable's value.

Is Null or Is Empty

Three variable names, one variable does not exists, other exists but value is empty, third one exists and value is space.

Test code:
string s = Environment.GetEnvironmentVariable("NO_SUCH_VARIABLE");
if (s == null) Console.WriteLine("Is Null");
else if (s == "") Console.WriteLine("Is Empty");

s = Environment.GetEnvironmentVariable("NO_SUCH_VARIABLE", EnvironmentVariableTarget.User);
if (s == null) Console.WriteLine("Is Null");
else if (s == "") Console.WriteLine("Is Empty");

s = Environment.GetEnvironmentVariable("EMPTY_VALUE_VARIABLE");
if (s == null) Console.WriteLine("Is Null");
else if (s == "") Console.WriteLine("Is Empty");

s = Environment.GetEnvironmentVariable("EMPTY_VALUE_VARIABLE", EnvironmentVariableTarget.User);
if (s == null) Console.WriteLine("Is Null");
else if (s == "") Console.WriteLine("Is Empty");

Result:
Is Null
Is Null
Is Null
Is Empty

tags: .net, c#, environment variable

Last edited Jul 11, 2012 at 1:22 PM by alekseiv, version 8

Comments

No comments yet.