1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Read Environment Variables with VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, Mar 22, 2007.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Windows stores some important information (e.g., computer name and user name) in the environment variables. The ability to access these variables to retrieve their values comes in handy in many applications. In this tip, I look at how you can use VB.NET to retrieve the information from the environment variables.

    In order to get information from the Windows environment variable, you need to determine the values of corresponding environment variables. VB.NET allows you to perform this operation by utilising two methods of the System.Environment class: GetEnvironmentVariable and GetEnvironmentVariables. The following examples show you how these classes work.

    Example 1

    In the following example, I define a variable to strComputerName. To determine the computer name, I utilise the method GetEnvironmentVariable of the Environment class and pass it to the specific name of the environment variable that I want to retrieve, which in this case is "COMPUTERNAME".

    Private Sub GetEnvironmentVariable()
          Dim strComputerName As String
          strComputerName = Environment.GetEnvironmentVariable("COMPUTERNAME")
      End Sub
    Example 2

    For this example, I added a listbox control, ListBox1, to the form and the code. I define the variable dictEntry as a DictionaryEntry. Then, I create a loop to go through all environment variables, utilising the GetEnvironmentVariables method of the Environment object. For every entry, I add a line to the listbox control with the key of the entry and its value.
      Private Sub GetEnvironmentVariables()
          Dim dictEntry As System.Collections.DictionaryEntry
          ForEach dictEntry In Environment.GetEnvironmentVariables()
              ListBox1.Items.Add("Key: " & (dictEntry.Key.ToString()) & "  Value: " & _
      End Sub

Share This Page