任何快速的方法来获得卷序列号?(Any faster method to get Volume Se

2019-09-19 07:34发布

您好我正在使用此代码来生成机器签名。 但它需要显着的时间来执行。 想知道为什么它这么慢? 推荐任何更快的方法?

Public Shared Function DriveSN(ByVal DriveLetter As String) As String
    Dim disk As ManagementObject = New ManagementObject(String.Format("Win32_Logicaldisk='{0}'", DriveLetter))
    Dim VolumeName As String = disk.Properties("VolumeName").Value.ToString()
    Dim SerialNumber As String = disk.Properties("VolumeSerialnumber").Value.ToString()
    Return SerialNumber.Insert(4, "-")
End Function

Private Shared msig As String = Nothing

Public Shared Function MachineSignature() As String
    If msig Is Nothing Then
        Dim list As New List(Of String)
        For Each d As DriveInfo In DriveInfo.GetDrives()
            If (d.IsReady) Then
                list.Add(DriveSN(d.Name.Substring(0, 2)))
            End If
        Next
        msig = String.Join(" & ", list.ToArray())
    End If
    Return msig
End Function

Answer 1:

这里是一个.NET的方式也从理论家网吧使用System.Management命名空间。

首先,您需要将引用添加到System.Management DLL在vb.net。 使用项目 - >添加引用菜单项。

然后将下面的代码将获取C盘驱动器的序列号:

Dim drive As String = "C"
Dim disk As System.Management.ManagementObject = _
       New System.Management.ManagementObject _
       ("win32_logicaldisk.deviceid=""" + drive + ":""")
disk.Get()
Dim SerialNumber as String = disk("VolumeSerialNumber").ToString()


Answer 2:

这是令人尴尬的。 性能问题可以简单地通过检查“固定”驱动器来解决。

Public Shared Function MachineSignature() As String
    If msig Is Nothing Then
        Dim list As New List(Of String)
        For Each d As DriveInfo In DriveInfo.GetDrives()
            If (d.DriveType = DriveType.Fixed) AndAlso (d.IsReady) Then  ' <-- check for DriveType'
                list.Add(DriveSN(d.Name.Substring(0, 2)))
            End If
        Next
        msig = String.Join(" & ", list.ToArray())
    End If
    Return msig
End Function


Answer 3:

有一个Win32 API调用此还,但我认为WMI是更好的办法,因为它仍然是托管代码。

Win32 API函数: GetVolumeInformation

我发现下面的函数eggheadcafe (这是C#,但应该不是问题,在vb.net做)提取序号:

public string GetVolumeSerial(string strDriveLetter)
{
uint serNum = 0;
uint maxCompLen = 0;
StringBuilder VolLabel = new StringBuilder(256); // Label
UInt32 VolFlags = new UInt32();
StringBuilder FSName = new StringBuilder(256); // File System Name
strDriveLetter+=":\\"; // fix up the passed-in drive letter for the API call
long Ret = GetVolumeInformation(strDriveLetter, VolLabel, (UInt32)VolLabel.Capacity, ref serNum, ref maxCompLen, ref VolFlags, FSName, (UInt32)FSName.Capacity);

return Convert.ToString(serNum);
}


文章来源: Any faster method to get Volume Serial number?
标签: .net vb.net wmi