Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   Read Environment Variables with VB.Net (http://www.go4expert.com/articles/read-environment-variables-vbnet-t3540/)

pradeep 22Mar2007 15:27

Read Environment Variables with VB.Net
 
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: VB

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: VB

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



All times are GMT +5.5. The time now is 16:07.