Read Environment Variables with VB.Net

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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".

    Code:
    Private Sub GetEnvironmentVariable()
          Dim strComputerName As String
          strComputerName = Environment.GetEnvironmentVariable("COMPUTERNAME")
          MessageBox.Show(strComputerName)
      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.
    Code:
      Private Sub GetEnvironmentVariables()
          Dim dictEntry As System.Collections.DictionaryEntry
          ForEach dictEntry In Environment.GetEnvironmentVariables()
              ListBox1.Items.Add("Key: " & (dictEntry.Key.ToString()) & "  Value: " & _
      (dictEntry.Value.ToString()))
          Next
      End Sub
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice