Environmental Awareness: Accessing Operating System Information, Special Folders, and More with Visual Basic 6 and the .NET Framework

 on Selasa, 14 Maret 2017  

Visual Studio .NET 2003
  Scott Swigart
Swigart Consulting LLC
April 2006
Applies to:
   Visual Basic 6
   .NET Framework
Summary: This article explains how you can use Visual Basic 6 with the .NET Framework to access user and operating system information that normally would require Win32 API calls. (8 printed pages)

Contents

Introduction
Spin the Wheel of Win32
Welcome to System.Environment
Wrapping It Up
All Boxed Up
Additional Resources
Click here to download the code sample for this article.

Introduction

There's a lot of user and operating system information that's typically been difficult to get to from Visual Basic 6; however, with a few trivial calls into the .NET Framework, this information is easy to retrieve.
Figure 1 illustrates the retrieval of user and operating system information from Visual Basic 6 with the .NET Framework.
Figure 1. Retrieving user and operating system information
You can see that this application retrieves the domain name, user name, and machine name. It also retrieves the string for the operating system version, letting you know what OS your code is running on. The logical drives are enumerated, and the IP addresses assigned to this machine are also listed—in this case, showing the physical and wireless IP addresses.
In addition, the application is able to retrieve the location for any of the special folders, which include:
  • Desktop
  • Programs
  • Personal
  • Favorites
  • StartUp
  • Recent
  • SendTo
  • StartMenu
  • MyMusic
  • DesktopDirectory
  • MyComputer
  • Templates
  • ApplicationData
  • LocalApplicationData
  • InternetCache
  • Cookies
  • History
  • CommonApplicationData
  • System
  • ProgramFiles
  • MyPictures
  • CommonProgramFiles

Spin the Wheel of Win32

To do this with 100% Visual Basic 6 would have required a lot of calls into the Win32 API, and all the goo that Win32 API calls entail. You would have to correctly create your Declare statements, craft structures that match what the API functions need, create buffers to hold strings, and so on. Not to mention that there are a number of API functions that do similar things, some of which are available on one operating system, but not others.

Welcome to System.Environment

The .NET Framework Class Library (FCL) organizes access to much of this system information under the System.Enviornment class. Tables 1 and 2 present a quick overview of this class, showing that it can provide a lot of information about the machine, user, and application environment.
Table 1. System.Environment properties
System.Environment Property Description Visual Basic 6 Equivalent
CommandLine Gets the command line for this process. Command function
CurrentDirectory Gets and sets the fully qualified path of the current directory—that is, the directory from which this process starts. App.Path
ExitCode Gets or sets the exit code of the process. No equivalent
HasShutdownStarted Indicates whether the common language runtime is shutting down, or whether the current application domain is unloading. Win32 API
MachineName Gets the NetBIOS name of this local computer. Win32 API
NewLine Gets the newline string defined for this environment. No equivalent
OSVersion Gets an OperatingSystem object that contains the current platform identifier and version number. Win32 API
StackTrace Gets current stack trace information. No equivalent
SystemDirectory Gets the fully qualified path of the system directory. Win32 API
TickCount Gets the number of milliseconds that have elapsed since the system started. Win32 API
UserDomainName Gets the network domain name associated with the current user. Win32 API
UserInteractive Gets a value indicating whether the current process is running in user interactive mode. Win32 API
UserName Gets the user name of the person who started the current thread. Win32 API
Version Gets a Version object that describes the major, minor, build, and revision numbers of the common language runtime. Win32 API
WorkingSet Gets the amount of physical memory mapped to the process context. Win32 API
Table 2. System.Environment methods
System.Environment Method Description Visual Basic 6 Equivalent
Exit Terminates this process and gives the underlying operating system the specified exit code. End or Win32 API
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. Environ function and custom code
GetCommandLineArgs Returns a string array containing the command-line arguments for the current process. Command function
GetEnvironmentVariable Returns the value of the specified environment variable. Environ function
GetEnvironmentVariables Returns all environment variables and their values. Environ function
GetFolderPath Gets the path to the system special folder identified by the specified enumeration. Win32 API
GetLogicalDrives Returns an array of strings containing the names of the logical drives on the current computer. Win32 API
As you can see from Tables 1 and 2, the System.Environment class provides a lot of information that isn't readily accessible from Visual Basic 6. To use the System.Environment class, you can create a simple COM wrapper class in Visual Basic .NET. Once the COM wrapper is created, you can use the System.Environment class from Visual Basic 6, VBA, ASP, VBScript, or any other environment that can use COM objects.

Wrapping It Up

To create a wrapper for the System.Environment class, you can just create a new Class Library project in Visual Studio .NET 2003, and add a COM Class to your project (see Figure 2).
Figure 2. Adding a COM Class to your project
You then simply create functions that call into the System.Environment methods and properties, and return the results (see Listing 1). In many cases, this involves just one line of code.
Listing 1. Returning System.Environment information from Visual Basic .NET
    Public Function GetLogicalDrives() As String()
        Return System.Environment.GetLogicalDrives()
    End Function

    Public Function GetMachineName() As String
        Return System.Environment.MachineName
    End Function

    Public Function GetOSVersion() As String
        Return System.Environment.OSVersion.ToString()
    End Function

    Public Function GetDomainName() As String
        Return System.Environment.UserDomainName()
    End Function

    Public Function GetUserName() As String
        Return System.Environment.UserName
    End Function

These functions can then be called from Visual Basic 6 to get the information (see Listing 2).
Listing 2. Accessing System.Environment from Visual Basic 6
    Set env = New NetFrameworkWrappers.EnvironmentWrapper
    txtDomainName = env.GetDomainName
    txtUserName = env.GetUserName
    txtMachineName = env.GetMachineName
    txtOsVersion = env.GetOSVersion

To get the directory for special folders, you need to specify which folder you're interested in. .NET provides an enumeration of all the possible folders, and this list can easily be provided to Visual Basic 6 as an array of strings (see Listing 3).
Listing 3. Returning the list of special folders from Visual Basic .NET
    Public Function ValidFolderPaths() As String()
        Return System.Enum.GetNames(GetType(SpecialFolder))
    End Function

This returns an array of strings with the identifiers for all the special folders. You can then pass in the ID of the special folder to get its directory location (see Listing 4).
Listing 4. Visual Basic .NET function that returns the directory location for a special folder
    Public Function GetFolderPath(ByVal specialName As String) As String
        Dim sf As SpecialFolder
        sf = System.Enum.Parse(GetType(SpecialFolder), specialName)
        Return System.Environment.GetFolderPath(sf)
    End Function

From Visual Basic 6, you can just call this function, pass in any special folder ID string, and get the location (see Listing 5).
Listing 5. Retrieving a special folder location from Visual Basic 6
    Set env = New NetFrameworkWrappers.EnvironmentWrapper
    txtMyPictures = env.GetFolderPath("MyPictures")

Information about the current system IP addresses isn't actually provided through System.Environment, but to me, it's part of the same theme. For this, I actually use classes in the System.Network namespace (see Listing 6).
Listing 6. Returning IP Addresses from Visual Basic .NET
    Public Function GetIpAddresses() As String()
        Dim h As System.Net.IPHostEntry = _
            System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
        Dim addresses(h.AddressList.Length - 1) As String
        For i As Integer = 0 To h.AddressList.Length - 1
            addresses(i) = h.AddressList(i).ToString()
        Next
        Return addresses
    End Function

This function first gets the host name for the computer using the Dns class. Then, it retrieves the IP addresses for that host name. The information is returned as an array of strings.

All Boxed Up

As a convenience, I've already created the wrapper class for System.Environment. The code for the wrapper, and the test application illustrated in Figure 1 are ready for you to download and experiment with. To install the COM wrapper, just execute install.bat, which is located in the download zip file. You can then find the Visual Basic 6 application in the VB6 Projects\Environment folder. The full .NET wrapper solution is available in the VB.NET Wrappers folder.
The theme of Visual Basic Fusion is that you can use everything that .NET offers from non-.NET environments such as Visual Basic 6, VBA, ASP, or VBScript. In this article, you've seen how you can access information that normally would have required Win32 API calls, with just a tiny bit of .NET code.



Tidak ada komentar:

Posting Komentar

Catatan: Hanya anggota dari blog ini yang dapat mengirim komentar.

B-Theme