ENVIRONMENT

Environment variables are values that a program can use to learn information about the system. There are three types of environment variables that apply at the system, user, and process levels. As you may guess from their names, system-level variables apply to all processes started on the system, user-level variables apply to processes started by a particular user, and process-level variables apply to a particular process and any other processes that it starts.

Environment variables may indicate such things as the name of the operating system, the location of temporary directories, the user’s name, and the number of processors the system has. You can also store configuration information in environment variables for your programs to use.

Environment variables are loaded when a process starts, and they are inherited by any process launched by the initial process. During Visual Basic development, that means the variables are loaded when you start Visual Studio and they are inherited by the program you are working on when you start it. If you make changes to the system’s environment variables, you need to close and reopen Visual Studio before your program will see the changes.

A program can also create temporary process-level variables that are inherited by launched processes and that disappear when the original process ends.

Visual Basic provides a couple of tools for working with the application’s environment. The following sections describe two: the Environ function and the System.Environment object. Before you can read environment variables, however, you should know how to set their values.

Setting Environment Variables

Environment variables are normally set on a systemwide basis before the program begins. In older operating systems, batch files such as autoexec.bat set these values. More recent systems provide Control Panel tools to set environment variables.

Newer systems also use an autoexec.nt file to set environment variables that apply only to command-line (console) applications so they don’t affect GUI applications. Sometimes you can use this fact to your advantage by giving different kinds of applications different environment settings.

To set environment variables in newer versions of Windows, open the Control Panel and search for the keyword “environment.” In Windows 8, open the search tool and search the Settings category for “environment.”

You should find two links with titles similar to “Edit environment variables for your account” and “Edit the system environment variables.” Click one of those links to display the System Properties dialog box’s Advanced tab. Click the Environment Variables button to add, remove, and modify environment variables.

Be careful to use the variables properly. Use system variables when a value should apply to all processes started by all users, user variables when a value should apply to all processes started by a particular user, and process variables when a value should apply to a process and any processes that it starts.


REMEMBER TO REFRESH
Remember that Visual Studio won’t see environment variable changes that you make after it is running. You need to close and reopen Visual Studio before your program will see the changes.

Using Environ

At run time, a Visual Basic application can use the Environ function to retrieve environment variable values. If you pass this function a number, it returns a string giving the statement that assigns the corresponding environment variable. For example, Environ(1) might return the following string:

ALLUSERSPROFILE=C:ProgramData

You should pass the function a number between 1 and 255. Environ returns a zero-length string if the number does not correspond to an environment variable. The following code uses this fact to list all of the application’s environment variables. When it finds a variable that has zero length, it knows it has read all of the variables with values.

For i As Integer = 1 To 255
    If Environ(i).Length = 0 Then Exit For
    Debug.WriteLine(i & ": " & Environ(i))
Next i

Example program ListEnviron uses similar code to display all of the environment variables’ assignment statements. Example program ListEnvironValues uses the String class’s Split method to separate the environment variables’ names and values and displays them in separate columns in a ListView control.

If you pass the Environ function the name of an environment variable, the function returns the variable’s value or Nothing if the variable does not exist. For example, the following code displays a greeting that includes the names of the user and the computer:

MessageBox.Show("Welcome " & Environ("USERNAME") & " on " & Environ("COMPUTERNAME"))

Using System.Environment

The Environ function is easy to use, but it’s not very flexible. It can read environment variable values but it cannot create or modify them.

The System.Environment object provides methods for getting and setting process-level environment variables. It also provides properties and methods for working with many other items in the application’s environment. The following table describes the Environment object’s most useful properties.

PROPERTY PURPOSE
CommandLine Returns the process’s command line.
CurrentDirectory Gets or sets the fully qualified path to the current directory.
ExitCode Gets or sets the process’s exit code. If the program starts from a Main function, that function’s return value also sets the exit code.
HasShutdownStarted Returns True if the Common Language Runtime is shutting down.
MachineName Returns the computer’s NetBIOS name.
NewLine Returns the environment’s defined new line string. For example, this might be a carriage return followed by a line feed.
OSVersion Returns an OperatingSystem object containing information about the operating system. This object provides the properties ServicePack (name of the most recent service pack installed), Version (includes Major, Minor, Build, and Revision; ToString combines them all), VersionString (combines the operating system name, version, and most recent service pack), and Platform, which can be UNIX, Win32NT (Windows NT or later), Win32S (runs on 16-bit Windows to provide access to 32-bit applications), Win32Windows (Windows 95 or later), or WinCE.
ProcessorCount Returns the number of processors on the computer.
StackTrace Returns a string describing the current stack trace.
SystemDirectory Returns the system directory’s fully qualified path.
TickCount Returns the number of milliseconds that have elapsed since the system started.
UserDomainName Returns the current user’s network domain name.
UserInteractive Returns True if the process is interactive. This only returns False if the application is a service process or web service.
UserName Returns the name of the user who started the process.
Version Returns a Version object describing the Common Language Runtime. This object provides the properties Major, Minor, Build, and Revision. Its ToString method combines them all.
WorkingSet Returns the amount of physical memory mapped to this process in bytes.

Example program SystemEnvironment displays the values of many of the Environment object’s properties.

The following table describes the Environment object’s most useful methods.

METHOD PURPOSE
Exit Ends the process immediately. Form Closing and Closed event handlers do not execute.
ExpandEnvironmentVariables Replaces environment variable names in a string with their values. For example, the following code displays the current user’s name: MessageBox.Show(Environment.ExpandEnvironmentVariables("I am %username%.")).
GetCommandLineArgs Returns an array of strings containing the application’s command-line arguments. The first entry (with index 0) is the name of the program’s executable file.
GetEnvironmentVariable Returns an environment variable’s value.
GetEnvironmentVariables Returns an IDictionary object containing the names and values of all environment variables.
GetFolderPath Returns the path to a system folder. This method’s parameter is a SpecialFolder enumeration value such as Cookies, Desktop, SendTo, or Recent. See the online help for a complete list of available folders.
GetLogicalDrives Returns an array of strings containing the names of the logical drives on the current computer.
SetEnvironmentVariable Creates, modifies, or deletes an environment variable.

The SetEnvironmentVariable method lets you set environment variables at the system, user, and process level. If you set a variable’s value to Nothing, this method deletes the variable. For system and user values, it updates the registry appropriately to set the values. Example program EnvironmentVariableLevels uses SetEnvironmentVariable to get and set variable values. For more information on the SetEnvironmentVariable method, see http://msdn2.microsoft.com/library/96xafkes.aspx.


NOTE Note that a program needs privilege to write to the registry to set a system-level environment variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.212.246