Sams Teach Yourself Visual Studio .NET 2003 in 21 Days

Sams Teach Yourself .Net in 21 Days

By Jason Beres

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.

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

Table 9.1. The Properties in the System.Environment Class

Property

Description

CommandLine

Gets the command line for this process.

CurrentDirectory

Gets and sets the fully qualified path of the current directory; that is, the directory from which this process starts.

ExitCode

Gets or sets the exit code of the process.

HasShutdownStarted

Indicates whether the common language runtime is shutting down.

MachineName

Gets the NetBIOS name of this local computer.

NewLine

Gets the newline string defined for this environment.

OSVersion

Gets an OperatingSystem object that contains the current platform identifier and version number.

StackTrace

Gets current stack trace information.

SystemDirectory

Gets the fully qualified path of the system directory.

TickCount

Gets the number of milliseconds elapsed since the system started.

UserDomainName

Gets the network domain name associated with the current user.

UserInteractive

Gets a value indicating whether the current process is running in user interactive mode.

UserName

Gets the username of the person who started the current thread.

Version

Gets a Version object that describes the major, minor, build, and revision numbers of the common language runtime.

WorkingSet

Gets 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

Method

Description

Exit

Terminates this process and gives the underlying operating system the specified exit code.

ExpandEnvironmentVariables

Replaces 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.

GetCommandLineArgs

Returns a string array containing the command-line arguments for the current process.

GetEnvironmentVariable

Returns the value of the specified environment variable.

GetEnvironmentVariables

Returns all environment variables and their values.

GetFolderPath

Gets the path to the system special folder identified by the specified enumeration.

GetLogicalDrives

Returns an array of string containing the names of the logical drives on the current computer.

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

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.)

09fig08.jpg

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.

Example 9.1. GetEnvironment_Click Event Code

vbnet_icon.gif
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

c_icon.gif
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.

09fig09.jpg

Figure 9.9 Output from the GetEnvironment click.

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

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.

Example 9.2. Getting the Logical Drives of Your Environment

vbnet_icon.gif
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

c_icon.gif
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:

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:

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.

09fig10.jpg

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.

Example 9.3. Getting Special Folders from Your Environment

vbnet_icon.gif
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

c_icon.gif
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.

09fig11.jpg

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:

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#.

Share ThisShare This

Informit Network