Working with Your Environment

The Environment class of the System namespace has properties and methods that enable you to interact with the environment that your application is running in. It also helps you retrieve specific information about the user who is currently logged on to the system that your applications are running on.

If you wrote applications using Visual Basic 6, you know that not many ways were built into the language to get information about the operating system, the version of either the OS or the version of Visual Basic, or even information about what the current user's name was. In .NET, the Environment class gives you more information than you need.

In this section, you learn how to retrieve information about the current state of the operating system and your application. You also learn how to get special operating system and user information, such as where special folders such as My Documents, Application Data, and the Windows directory are located.

Note

Getting specific information about the logged-in user, such as folder names and locations, is extremely important with Windows 2000 and greater. The idea of a mobile user who has system folders, such as My Documents, located on a server instead of the local machine is common now. The more companies move to thinner clients, the more likely it is that the end user won't have these folders on her local machine, so you need a way to determine where these folders are located. The Environment class helps you do just that.


The properties of the Environment class are listed in Table 9.1.

Table 9.1. The Properties in the System.Environment Class
PropertyDescription
CommandLineGets the command line for this process.
CurrentDirectoryGets and sets the fully qualified path of the current directory; that is, the directory from which this process starts.
ExitCodeGets or sets the exit code of the process.
HasShutdownStartedIndicates whether the common language runtime is shutting down.
MachineNameGets the NetBIOS name of this local computer.
NewLineGets the newline string defined for this environment.
OSVersionGets an OperatingSystem object that contains the current platform identifier and version number.
StackTraceGets current stack trace information.
SystemDirectoryGets the fully qualified path of the system directory.
TickCountGets the number of milliseconds elapsed since the system started.
UserDomainNameGets the network domain name associated with the current user.
UserInteractiveGets a value indicating whether the current process is running in user interactive mode.
UserNameGets the username of the person who started the current thread.
VersionGets a Version object that describes the major, minor, build, and revision numbers of the common language runtime.
WorkingSetGets the amount of physical memory mapped to the process context.

Although there are times when you might need to retrieve specific information about environment variables, it might be more common to need to know what logical drives are on a system and the names and locations of the special folders, such as My Documents. You can get this type of information by using the methods of the Environment class. Table 9.2 lists the common methods you can use to get specific information about the current environment and the current user.

Table 9.2. The Methods in the System.Environment Class
MethodDescription
ExitTerminates this process and gives the underlying operating system the specified exit code.
ExpandEnvironmentVariablesReplaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, and then returns the resulting string.
GetCommandLineArgsReturns a string array containing the command-line arguments for the current process.
GetEnvironmentVariableReturns the value of the specified environment variable.
GetEnvironmentVariablesReturns all environment variables and their values.
GetFolderPathGets the path to the system special folder identified by the specified enumeration.
GetLogicalDrivesReturns an array of string containing the names of the logical drives on the current computer.

Note

Several methods of the Environment class return a string array of information. Whenever a description of a method says something like “Returns a collection” or “Returns an array,” you must know the correct way to declare the variable that will hold the returning data, and you must iterate through the data to get each piece of information. The code you write in Listing 9.2 uses the For Each method in Visual Basic .NET and the foreach method in C# to iterate through the data returned in the string array. The string array was declared by simply adding parentheses after the Visual Basic .NET variable declaration or brackets after the C# variable declaration, like this:

Dim myStringArray() as String

string[] myStringArray;

If you forget to add the brackets or parentheses, you'll get an error. Yesterday you learned how to deal with arrays in several different ways. You can refer to that lesson to refresh your memory on all the capabilities of arrays.


Creating the Environment Sample Application

To use the Environment class in real life, you're going to write a Windows Forms application that uses most of the properties and methods covered in Tables 9.1 and 9.2. This exercise is very important because you learn how to

  • Use the properties and methods of the Environment class

  • Declare an array and iterate through the items of an array

  • Learn the basics of the ListView control—a very useful GUI control

Follow these steps to set up the new application. But before you start, look at Figure 9.8 to see what the end result of your form should look like.

1.
Create a new Windows Forms application named Environment_Winforms.

2.
On the default form1, change the following properties using the Properties window:

Name = mainForm

Text = "Environment Settings"

Font = Tahoma, 10pt

StartupPosition = CenterScreen

3.
Next, drag a button from the Toolbox onto the form, and change these properties:

Name = GetEnvironment

Text = "Get My Environment"

4.
Drag another button from the Toolbox onto the form, and change these properties:

Name = GetDrives

Text = "Get Logical Drives"

5.
Drag another button from the Toolbox onto the form, and change these properties:

Name = GetSpecialFolders

Text = "Get Special Folders"

6.
Drag a ListView object from the Toolbox onto the form, and change these properties:

Name = EnvironmentListView

Anchor = Top, Left, Bottom, Right

Columns = Click the ellipses button that appears when you click the Columns property in the Properties window. The custom designer for adding columns to this list view pops up. Click the Add button on the custom designer twice, and change the Text property for the first column to "Name" by clicking on the first item on the left list box, which will be called ColumnHeader1. After you click the item on the left, you can change the Text property on the right side of the designer. Change the Text property for the second column to "Description". Click OK to close the custom designer.

View = Details (By selecting Details, the column headers for the list view are visible. Like using Windows Explorer or My Computer, if you're viewing large icons, small icons, or lists, you won't see the column headers.)

Figure 9.8. Environment_WinForms form after adding controls.


Your newly created mainForm should look like Figure 9.8.

Using the Properties of the Environment Class

Now that you've set up the project, you can start writing the code to retrieve environment information. The first thing you'll do is add some code-behind for the Get My Environment button, which gets some of the properties of the Environment class listed in Table 9.1. Double-click the Get My Environment button and add the following code-behind for the GetEnvironment_Click event shown in Listing 9.1.

Listing 9.1. GetEnvironment_Click Event Code
Private Sub GetEnvironment_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles GetEnvironment.Click

 ' Set the cursor to an hourglass
 Me.Cursor = Cursors.WaitCursor

 With EnvironmentListView

  ' Clear the ListView of any existing items
  .Items.Clear()

  ' Create a ListItem variable
  Dim lvi As ListViewItem

  ' Create a new instance of the ListItem variable
  ' and re-use it for each property you add to the ListView
  lvi = New ListViewItem()
  With lvi
   .Text = "Current Directory"
   .SubItems.Add(Environment.CurrentDirectory)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "Machine Name"
   .SubItems.Add(Environment.MachineName)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "OS Version"

   ' NOTE: Call the ToString method to convert the Number
   ' to a string variable for display
   .SubItems.Add(Environment.OSVersion.ToString)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "System Directory"
   .SubItems.Add(Environment.SystemDirectory)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "Ticks since last shutdown"
   .SubItems.Add(Environment.TickCount)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "User Domain Name"
   .SubItems.Add(Environment.UserDomainName)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "User Name"
   ' NOTE: Call the ToString method to convert the Number
   ' to a string variable for display
   .SubItems.Add(Environment.UserName)
  End With
  .Items.Add(lvi)

  lvi = New ListViewItem()
  With lvi
   .Text = "User Domain Name"
   .SubItems.Add(Environment.Version.ToString)
  End With
  .Items.Add(lvi)
 End With

 ' Set the cursor back to normal
 Me.Cursor = Cursors.Default

End Sub


private void getEnvironment_Click(object sender, System.EventArgs e)
 {

  // Set the cursor to an hourglass
  this.Cursor = Cursors.WaitCursor;

  // Clear the ListView of any existing items
  EnvironmentListView.Items.Clear();

  // Create a ListItem variable
  ListViewItem lvi;

  // Create a new instance of the ListItem variable
  // and re-use it for each property you add to the ListView
  lvi = new ListViewItem();

  lvi.Text = "Current Directory";
  lvi.SubItems.Add(Environment.CurrentDirectory);
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "Machine Name";
  lvi.SubItems.Add(Environment.MachineName);
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "OS Version";
  lvi.SubItems.Add(Environment.OSVersion.ToString());
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "System Directory";
  lvi.SubItems.Add(Environment.SystemDirectory);
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "Ticks since last shutdown";
  lvi.SubItems.Add(Environment.TickCount.ToString());
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "User Domain Name";
  lvi.SubItems.Add(Environment.UserDomainName);
  EnvironmentListView.Items.Add(lvi);

  lvi = new ListViewItem();
  lvi.Text = "User Name";
  lvi.SubItems.Add(Environment.UserName);
  EnvironmentListView.Items.Add(lvi);

  // Set the cursor back to normal
  this.Cursor = Cursors.Default;
  }
 }

If you press the F5 key to run the application and click the Get My Environment button, you should see something similar to Figure 9.9.

Figure 9.9. Output from the GetEnvironment click.


Here are some key points in the code you just wrote:

  • You set the correct mouse cursor to the hourglass by setting the cursor with Cursor = Cursors.WaitCursor, and then back to the default cursor by calling Cursor = Cursor.Default after the procedure finishes.

  • You created a ListViewItem variable called lvi. For each item you wanted to add to the ListView control, you created a new instance of the ListView item and set properties on it. The Text property is always the first column of the ListView control. To add additional columns, you use the Add method of the SubItems property. After you've added the Text and the SubItems, you call the Add method on the ListView to actually display the data. The following snippet does exactly that:

    lvi.Text = "Current Directory";
    lvi.SubItems.Add(Environment.CurrentDirectory);
    EnvironmentListView.Items.Add(lvi);
    
  • Each SubItem you added to the ListViewItem retrieved a property of the Environment class, such as CurrentDirectory or UserName.

Using the GetLogicalDrives Method

Next, you need to add some code to the click event for the Get Logical Drives button. Double-click the Get Logical Drive button on your form, and add the code shown in Listing 9.2 to the GetDrives_Click event that retrieves the drives for the system and displays them in the ListView control.

Listing 9.2. Getting the Logical Drives of Your Environment
Private Sub GetDrives_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles GetDrives.Click
 ' Set the cursor to an hourglass
 Me.Cursor = Cursors.WaitCursor

 ' Clear the ListView
 EnvironmentListView.Items.Clear()

 ' Declare a string array called logicalDrives and call the
 ' GetLogicalDrives method of the Environment class
 Dim logicalDrives As String() = Environment.GetLogicalDrives()

 ' Create a string variable so we can loop
 ' through the array using For Each
 Dim drive As String

 ' Create a ListView Item variable
 Dim lvi As ListViewItem

 ' Look for each drive variable in the logicalDrives string array
 For Each drive In logicalDrives
  With EnvironmentListView
   lvi = New ListViewItem()
   With lvi
    .Text = "Drive Letter"
    .SubItems.Add(drive)
   End With
   .Items.Add(lvi)
  End With
 Next drive

 ' Set the cursor back to normal
 Me.Cursor = Cursors.Default

End Sub


private void getDrives_Click(object sender, System.EventArgs e)
 {

  // Set the cursor to an hourglass
  this.Cursor = Cursors.WaitCursor;

  // Clear the ListView of any existing items
  EnvironmentListView.Items.Clear();

  // Create a ListItem variable
  ListViewItem lvi;

  // Create a string array variable called logicalDrives
  string[] logicalDrives;

  // Call the GetLogicalDrives method of the Environment class
  logicalDrives = Environment.GetLogicalDrives();

  // Loop thru the collection of drives, and add them to the ListView
  foreach(string drives in logicalDrives)
  {
  // Create a new instance of the ListItem variable
  // and re-use it for each property you add to the ListView
  lvi = new ListViewItem();
  lvi.Text = "Drive Letter";
  lvi.SubItems.Add(drives);
  EnvironmentListView.Items.Add(lvi);
  }

  // Set the cursor back to normal
  this.Cursor = Cursors.Default;

 }

If you now run the application by pressing the F5 key, you'll get a list of the logical drives on your system. Building on the previous code you wrote for the GetEnvironment_Click event, you're still using the ListItem variable to add items to the list view. The differences in what you did are as follows:

  • The GetLogicalDrives method returns a string array. At this point, you have all the data you need to display in a string array, which makes it easier to write out because you can just write some looping code to do so.

  • To loop through the array, you create a drives string variable. With each iteration of the loop (using For Each in Visual Basic .NET or foreach in C#), you created the new instance of the ListItem variable, set the Text property to "Drive Letter", and set the SubItem to the item in the logicalDrives string array you're looping through.

  • You call the EnvironmentListView.Items.Add method for each item in the array as you looped through, and the item was then displayed in the ListView.

  • As before, you set the screen cursor to Wait at the beginning of the procedure and Default at the end to give the user interface some consistency.

Getting Special System Folders with the SpecialFolder Enumeration

To finish this Environment lesson, you must get the special folders in the system using the GetFolderPath method. This method is slightly different from what you used previously because it uses an enumeration called SpecialFolder that contains the friendly names of the special folders. As you learned yesterday, enumerations are like arrays, but actually just present information to you in a user-friendly manner, not the underlying numeric value that the information represents. The SpecialFolder enumeration contains the path to the following directories on the system:

  • ApplicationData

  • CommonApplicationData

  • CommonProgramFile

  • Cookies

  • DesktopDirectory

  • Favorites

  • History

  • InternetCache

  • LocalApplicationData

  • Personal

  • ProgramFiles

  • Programs

  • Recent

  • SendTo

  • StartMenu

  • Startup

  • System

  • Templates

In Visual Studio .NET, figuring out the enumeration values is very easy, thanks to the auto list members feature. If you don't feel like looking up the enumeration values for the SpecialFolder enumeration in the SDK, you can just take a few good guesses, as I did in Figure 9.10.

Figure 9.10. Figuring out the SpecialFolder enumeration.


So, let's now finish the application and get the special folder values. Double-click the Get Special Folders button, and add the code in Listing 9.3 to the GetSpecialFolders_Click event in the code-behind.

Listing 9.3. Getting Special Folders from Your Environment
Private Sub GetSpecialFolders_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles GetSpecialFolders.Click

 ' Set the cursor to an hourglass
 Me.Cursor = Cursors.WaitCursor

 With EnvironmentListView.Items

  ' Clear the ListView of any existing items
  .Clear()

  .Add("Program Files Folder").SubItems.Add _
     (Environment.GetFolderPath _
     (Environment.SpecialFolder.ProgramFiles))

  .Add("Application Data").SubItems.Add _
    (Environment.GetFolderPath _
    (Environment.SpecialFolder.ApplicationData))

  .Add("Personal Folder").SubItems.Add _
    (Environment.GetFolderPath _
    (Environment.SpecialFolder.Personal))

  .Add("Local Application Data Folder").SubItems.Add _
    (Environment.GetFolderPath _
    (Environment.SpecialFolder.ApplicationData))

 End With

 Me.Cursor = Cursors.Default

End Sub


private void getSpecialFolders_Click(object sender, System.EventArgs e)
 {
  // Set the cursor to an hourglass
  this.Cursor = Cursors.WaitCursor;

  // Clear the ListView of any existing items
  EnvironmentListView.Items.Clear();

  // Call the GetFolderPath method, passing the
  // SpecialFolder enumeration variable to get the special Folder
  EnvironmentListView.Items.Add("Program Files").SubItems.Add
   (Environment.GetFolderPath
   (Environment.SpecialFolder.ProgramFiles));

  EnvironmentListView.Items.Add("Application Data").SubItems.Add
   (Environment.GetFolderPath
   (Environment.SpecialFolder.ApplicationData));

  EnvironmentListView.Items.Add("Personal Folder").SubItems.Add
   (Environment.GetFolderPath
   (Environment.SpecialFolder.Personal));

  EnvironmentListView.Items.Add("Local Application Data").SubItems.Add
   (Environment.GetFolderPath
   (Environment.SpecialFolder.LocalApplicationData));

  // Set the cursor back to normal
  this.Cursor = Cursors.Default;

 }

Run the application and click the Get Special Folders button. You should see something similar to Figure 9.11.

Figure 9.11. Output from the GetFolderPath method.


The code you wrote for the GetSpecialFolders_Click event is almost identical to the code you wrote for the GetEnvironment_Click click event in Listing 9.1. There are two main differences:

  • Instead of creating the ListItem variable, you add the ListItem and its corresponding SubItem in the same line of code. Either method of adding ListItems and SubItems is acceptable; use the approach that's easiest for you to implement and remember.

  • You call the GetFolderPath method and use the SpecialFolder enumeration to display in the ListView, not the properties of the Environment class.

You now have a good understanding of how you can use the Environment class to retrieve information about the environment that your application is running in. You should also have a good grasp on using the ListView control and the For Each statement in Visual Basic .NET and the foreach statement in C#.

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

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