任何更快的方法来获得卷序列号?

时间:2009-07-17 10:56:49

标签: .net vb.net wmi

您好我正在使用此代码生成机器签名。但这需要花费很长时间才能执行。不知道为什么这么慢?建议使用更快的方法吗?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

还有一个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);
}