ProblemYour program relies on data stored in DOS-style environment variables, and you're ready to retrieve some of those values. SolutionUse the My.Application. GetEnvironmentVariable() method to retrieve specific environment variable values. DiscussionMicrosoft's MS-DOS operating system predated Windows, and when Windows was first released, it needed to use and support many of the existing MS-DOS features. One such feature involved environment variables, a collection of name/value pairs that served as a set of global constants programs could read and use. For instance, the PATH variable stored a list of directories Windows used to locate programs. Other applications could read the PATH variable for their own use. To retrieve the PATH environment variable from Visual Basic, use this statement: Dim thePath As String = _ My.Application.GetEnvironmentVariable("PATH") An error occurs if you supply a variable name that does not exist. If it does exist, the method returns just the value of the variable, not its name. Visual Basic also includes a built-in Environ() function that provides similar functionality: Dim thePath As String = Environ("PATH") If the supplied variable name cannot be found, Environ() returns an empty string without raising an error. Environ() also retrieves environment variables by numeric position. The following code scans through the set of environment variables until it hits a blank result, indicating the end of the set of variables: Dim counter As Integer Dim fullVariable As String Dim namePart As String Dim valuePart As String Dim equalsPosition As Integer For counter = 1 To 255 fullVariable = Environ(counter) If (fullVariable = "") Then Exit For equalsPosition = InStr(fullVariable, "=") If (equalsPosition > 0) Then namePart = Left(fullVariable, equalsPosition - 1) valuePart = Mid(fullVariable, equalsPosition + 1) ' ----- Use these values as needed. End If Next counter See AlsoFor additional information on environment variables, see the online help included with Microsoft Windows. On Windows XP, access help from the Start button (Start Help), and search for "environment variables." |