• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 243
  • Last Modified:

Can someone clean up this function for me?

This function seems inefficient.

I want it to just return the clients(user) mac address with as little code as possible.

Imports System.Management

Private Function GetMacAddress() As String

        Dim mc As System.Management.ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
        Dim moc As ManagementObjectCollection = mc.GetInstances()
        Dim mo As ManagementObject

        Dim strMacAddress As String = "N/A"
        For Each mo In moc
            If mo.Item("IPEnabled") Then
                strMacAddress = mo.Item("MacAddress").ToString()
            End If
        Next

        If IsNothing(strMacAddress) Then
            Return "n/a"
        Else
            Return strMacAddress
        End If

    End Function
0
Hepen
Asked:
Hepen
1 Solution
 
ZeonFlashCommented:
Since you appear to be retrieving only one valid value from the list, you can cut down on some operations by returning as soon as you get a valid value, ie:

Private Function GetMacAddress() As String

        Dim mc As System.Management.ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
        Dim moc As ManagementObjectCollection = mc.GetInstances()
        Dim mo As ManagementObject

        For Each mo In moc
           If mo.Item("IPEnabled") Then
              Return CStr(mo.Item("MacAddress"))
           End If
        Next

        Return "n/a"

End Function

Worst case, the last item in the list is the one you want.  But in most cases, you'll return the value without looping through the rest of the list.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now