Environment Variables in Visual Basic .NET
Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in Visual Basic .NET.
Imports System
Imports System.Environment
Module EnvironmentVariables
Sub Main()
' To set a key/value pair, use Environment.SetEnvironmentVariable
' To get a value for a key, use Environment.GetEnvironmentVariable
' This will return Nothing if the key isn't present in the environment.
Environment.SetEnvironmentVariable("FOO", "1")
Console.WriteLine("FOO: " & Environment.GetEnvironmentVariable("FOO"))
Console.WriteLine("BAR: " & Environment.GetEnvironmentVariable("BAR"))
' Use Environment.GetEnvironmentVariables to get all key/value pairs in the
' environment. This returns an IDictionary. Here we print all the keys.
Console.WriteLine()
For Each de As DictionaryEntry In Environment.GetEnvironmentVariables()
Console.WriteLine(de.Key)
Next
End Sub
End Module
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
FOO: 1
BAR:
The list of keys in the environment will depend on your particular machine.
PROCESSOR_ARCHITECTURE
PATH
TEMP
...
FOO
If we set BAR
in the environment first, the running program picks that value up. In Visual Basic .NET, you can set environment variables before running the program using the command prompt:
C:\> set BAR=2
C:\> vbc EnvironmentVariables.vb
C:\> EnvironmentVariables.exe
FOO: 1
BAR: 2
...
Note that the exact method of setting environment variables and compiling/running the program may vary depending on your development environment and Visual Studio settings.