elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Obtener número de serie de un disco físico (no volumen lógico)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Obtener número de serie de un disco físico (no volumen lógico)  (Leído 4,828 veces)
bybaal

Desconectado Desconectado

Mensajes: 52


Ver Perfil
Obtener número de serie de un disco físico (no volumen lógico)
« en: 3 Febrero 2021, 04:46 am »

Alguien me pudiera aclarar como se puede obtener el número de serie de un disco físico, también el modelo del disco.

OJO!!! Que sea usando la API de Windows y en VB


En línea

BlackZeroX
Wiki

Desconectado Desconectado

Mensajes: 3.158


I'Love...!¡.


Ver Perfil WWW
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #1 en: 3 Febrero 2021, 05:56 am »

Alguien me pudiera aclarar como se puede obtener el número de serie de un disco físico, también el modelo del disco.

OJO!!! Que sea usando la API de Windows y en VB

GetVolumeInformationA function (fileapi.h)

https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumeinformationa

Encontré el uso en C/C++ solo tradúcelo y adáptalo a tus necesidades que tampoco creo en los foros se hagan encargos de codigo a modo.

https://gist.github.com/micjabbour/a2fbe50160862e6abe439c0b0769c3fb

Lo modifique para listara los números de serie de todos los discos físicos instalados (es un asco como lo adapte, lo se jajajaja).
Código
  1. #include <windows.h>
  2. #include <memory>
  3. #include <string>
  4. #include <iostream>
  5. #include <bitset>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. #define CTL_CODE(DeviceType, Function, Method, Access) \
  11.     (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  12. #define METHOD_BUFFERED 0
  13.  
  14. //returns the serial number of the first physical drive in a string or an empty string in case of failure
  15. //based on http://codexpert.ro/blog/2013/10/26/get-physical-drive-serial-number-part-1/
  16. string getFirstHddSerialNumber(wchar_t *pDisk) {
  17.    //get a handle to the first physical drive
  18.    HANDLE h = CreateFileW(pDisk, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  19.    if(h == INVALID_HANDLE_VALUE) return {};
  20.    //an unique_ptr is used to perform cleanup automatically when returning (i.e. to avoid code duplication)
  21.    unique_ptr<remove_pointer<HANDLE>::type, void(*)(HANDLE)> hDevice{h, [](HANDLE handle){CloseHandle(handle);}};
  22.    //initialize a STORAGE_PROPERTY_QUERY data structure (to be used as input to DeviceIoControl)
  23.    STORAGE_PROPERTY_QUERY storagePropertyQuery{};
  24.    storagePropertyQuery.PropertyId= StorageDeviceProperty;
  25.    storagePropertyQuery.QueryType= PropertyStandardQuery;
  26.    //initialize a STORAGE_DESCRIPTOR_HEADER data structure (to be used as output from DeviceIoControl)
  27.    STORAGE_DESCRIPTOR_HEADER storageDescriptorHeader{};
  28.    //the next call to DeviceIoControl retrieves necessary size (in order to allocate a suitable buffer)
  29.    //call DeviceIoControl and return an empty string on failure
  30.    DWORD dwBytesReturned= 0;
  31.    if(!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
  32.                        &storageDescriptorHeader, sizeof(STORAGE_DESCRIPTOR_HEADER), &dwBytesReturned, NULL))
  33.        return {};
  34.    //allocate a suitable buffer
  35.    const DWORD dwOutBufferSize= storageDescriptorHeader.Size;
  36.    unique_ptr<BYTE[]> pOutBuffer{new BYTE[dwOutBufferSize]{}};
  37.    //call DeviceIoControl with the allocated buffer
  38.    if(!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
  39.                        pOutBuffer.get(), dwOutBufferSize, &dwBytesReturned, NULL))
  40.        return {};
  41.    //read and return the serial number out of the output buffer
  42.    STORAGE_DEVICE_DESCRIPTOR* pDeviceDescriptor= reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(pOutBuffer.get());
  43.    const DWORD dwSerialNumberOffset= pDeviceDescriptor->SerialNumberOffset;
  44.    if(dwSerialNumberOffset==0) return {};
  45.    const char* serialNumber= reinterpret_cast<const char*>(pOutBuffer.get() + dwSerialNumberOffset);
  46.    return serialNumber;
  47. }
  48.  
  49. void printPhysicalDriversSerial() {
  50.    bitset<32> drives(GetLogicalDrives());
  51.    vector<char> goodDrives;
  52.    for (char c = 'A'; c <= 'Z'; ++c) {
  53.        if (drives[c - 'A']) {
  54.            //if (GetDriveType((c + string(":\\")).c_str()) == DRIVE_FIXED) { descomentar para solo obtener los Discos físicos internos.
  55.                goodDrives.push_back(c);
  56.            //}
  57.        }
  58.    }
  59.    for (auto & drive : goodDrives) {
  60.        string s = string("\\\\.\\") + drive + ":";
  61.        HANDLE h = CreateFileA(
  62.            s.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  63.            OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS, NULL
  64.        );
  65.        if (h == INVALID_HANDLE_VALUE) {
  66.            cerr << "Drive " << drive << ":\\ cannot be opened" << endl;
  67.            continue;
  68.        }
  69.        DWORD bytesReturned;
  70.        VOLUME_DISK_EXTENTS vde;
  71.        if (!DeviceIoControl(
  72.            h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
  73.            NULL, 0, &vde, sizeof(vde), &bytesReturned, NULL
  74.        )) {
  75.            cerr << "Drive " << drive << ":\\ cannot be mapped into physical drive" << endl;
  76.            continue;
  77.        }
  78.        for (int i = 0; i < vde.NumberOfDiskExtents; ++i) {
  79.            wchar_t disk [MAX_PATH];
  80.            swprintf(disk, MAX_PATH, L"\\\\.\\PhysicalDrive%d", vde.Extents[i].DiskNumber);
  81.            string serialNumber = getFirstHddSerialNumber(disk);
  82.            fputws ( disk, stdout );
  83.            cout << endl;
  84.            if(serialNumber.empty()) {
  85.                cout << "failed to retrieve serial number" << endl;
  86.            } else {
  87.                cout << "serial number: " << serialNumber << endl;
  88.            }
  89.        }
  90.    }
  91. }
  92.  
  93. int main() {
  94.    printPhysicalDriversSerial();
  95.    return 0;
  96. }
  97.  

Para corroborar los datos pintados, ejecutar en CMD:

wmic diskdrive get Name, Manufacturer, Model, InterfaceType, MediaType, SerialNumber

Saludos.


« Última modificación: 3 Febrero 2021, 07:15 am por BlackZeroX (Astaroth) » En línea

The Dark Shadow is my passion.
bybaal

Desconectado Desconectado

Mensajes: 52


Ver Perfil
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #2 en: 3 Febrero 2021, 18:28 pm »

Buscando me he encontrado un código en vb6, pero me parece que no logró adaptarlo correctamente a vb.net, ya que me genera un error cuando se va a usar la api ZeroMemory

Alguien que tenga alguna idea de que hay que corregir, ya que a mi no se me ocurre nada más

Código
  1. Private Declare Auto Function CreateFile _
  2.        Lib "kernel32" Alias "CreateFileA" (
  3.            ByVal lpFileName As String,
  4.            ByVal dwDesiredAccess As Integer,
  5.            ByVal dwShareMode As Integer,
  6.            ByVal lpSecurityAttributes As Integer,
  7.            ByVal dwCreationDisposition As Integer,
  8.            ByVal dwFlagsAndAttributes As Integer,
  9.            ByVal hTemplateFile As IntPtr
  10.        ) As Integer
  11.  
  12.    Private Declare Auto Function CloseHandle _
  13.        Lib "kernel32" (
  14.            ByVal hObject As IntPtr
  15.        ) As Integer
  16.  
  17.    Private Declare Auto Function DeviceIoControl _
  18.        Lib "kernel32" (
  19.            ByVal hDevice As IntPtr,
  20.            ByVal dwIoControlCode As Integer,
  21.            <MarshalAs(UnmanagedType.AsAny)>
  22.            lpInBuffer As Object,
  23.            ByVal nInBufferSize As Integer,
  24.            <MarshalAs(UnmanagedType.AsAny)>
  25.            lpOutBuffer As Object,
  26.            ByVal nOutBufferSize As Integer,
  27.            lpBytesReturned As Integer,
  28.            ByVal lpOverlapped As Integer
  29.        ) As Integer
  30.  
  31.    Private Declare Auto Sub ZeroMemory _
  32.        Lib "kernel32" Alias "RtlZeroMemory" (
  33.            <MarshalAs(UnmanagedType.AsAny)>
  34.            dest As Object,
  35.            ByVal numBytes As Integer)
  36.  
  37.    'Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Object, Source As Object, ByVal Length As Integer)
  38.    Private Declare Auto Function GetLastError Lib "kernel32" () As Integer
  39.  
  40.    Private Const DFP_RECEIVE_DRIVE_DATA = &H7C088
  41.    Private Const FILE_SHARE_READ = &H1
  42.    Private Const FILE_SHARE_WRITE = &H2
  43.    Private Const GENERIC_READ = &H80000000
  44.    Private Const GENERIC_WRITE = &H40000000
  45.    Private Const OPEN_EXISTING = 3
  46.    Private Const CREATE_NEW = 1
  47.  
  48.    Private Enum HDInfo
  49.        HD_MODEL_NUMBER = 0
  50.        HD_SERIAL_NUMBER = 1
  51.        HD_FIRMWARE_REVISION = 2
  52.    End Enum
  53.  
  54.    Private Structure IDEREGS
  55.        Public bFeaturesReg As Byte
  56.        Public bSectorCountReg As Byte
  57.        Public bSectorNumberReg As Byte
  58.        Public bCylLowReg As Byte
  59.        Public bCylHighReg As Byte
  60.        Public bDriveHeadReg As Byte
  61.        Public bCommandReg As Byte
  62.        Public bReserved As Byte
  63.    End Structure
  64.  
  65.    Private Structure SENDCMDINPARAMS
  66.        Public cBufferSize As Integer
  67.        Public irDriveRegs As IDEREGS
  68.        Public bDriveNumber As Byte
  69.        <VBFixedArray(1, 3)>
  70.        Public bReserved() As Byte
  71.        <VBFixedArray(1, 4)>
  72.        Public dwReserved() As Integer
  73.    End Structure
  74.  
  75.    Private Structure DRIVERSTATUS
  76.        Public bDriveError As Byte
  77.        Public bIDEStatus As Byte
  78.        <VBFixedArray(1, 2)>
  79.        Public bReserved() As Byte
  80.        <VBFixedArray(1, 2)>
  81.        Public dwReserved() As Integer
  82.    End Structure
  83.  
  84.    Private Structure SENDCMDOUTPARAMS
  85.        Public cBufferSize As Integer
  86.        Public DStatus As DRIVERSTATUS
  87.        <VBFixedArray(1, 512)>
  88.        Public bBuffer() As Byte
  89.    End Structure
  90.  
  91.    Private mvarCurrentDrive As Byte
  92.  
  93.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  94.        MsgBox(GetHDDInfo(0, "serial"))
  95.        End
  96.    End Sub
  97.  
  98.    Public Function GetHDDInfo(ByVal Number As Byte, ByVal Cmd As String) As String
  99.        mvarCurrentDrive = Number
  100.  
  101.        Select Case LCase(Cmd)
  102.            Case "model" : GetHDDInfo = CmnGetHDData(HDInfo.HD_MODEL_NUMBER)
  103.            Case "serial" : GetHDDInfo = CmnGetHDData(HDInfo.HD_SERIAL_NUMBER)
  104.            Case "firmware" : GetHDDInfo = CmnGetHDData(HDInfo.HD_FIRMWARE_REVISION)
  105.            Case Else : GetHDDInfo = ""
  106.        End Select
  107.    End Function
  108.  
  109.    Private Function CmnGetHDData(hdi As HDInfo) As String
  110.        Dim Bin As SENDCMDINPARAMS
  111.        Dim Bout As SENDCMDOUTPARAMS
  112.        Dim hdh As Long
  113.        Dim br As Long
  114.        Dim Ix As Long
  115.        Dim hddfr As Long
  116.        Dim hddln As Long
  117.        Dim S As String
  118.  
  119.        Select Case hdi
  120.            Case HDInfo.HD_MODEL_NUMBER
  121.                hddfr = 55
  122.                hddln = 40
  123.            Case HDInfo.HD_SERIAL_NUMBER
  124.                hddfr = 21
  125.                hddln = 20
  126.            Case HDInfo.HD_FIRMWARE_REVISION
  127.                hddfr = 47
  128.                hddln = 8
  129.            Case Else : Err.Raise(10001, "Illegal HD Data type")
  130.        End Select
  131.        hdh = CreateFile("\\.\PhysicalDrive" & mvarCurrentDrive, GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
  132.  
  133.        If hdh = 0 Then Err.Raise(10003, , "Error on CreateFile")
  134.  
  135.        ZeroMemory(Bin, Len(Bin))
  136.        ZeroMemory(Bout, Len(Bout))
  137.  
  138.        With Bin
  139.            .bDriveNumber = mvarCurrentDrive
  140.            .cBufferSize = 512
  141.            With .irDriveRegs
  142.                If (mvarCurrentDrive And 1) Then
  143.                    .bDriveHeadReg = &HB0
  144.                Else
  145.                    .bDriveHeadReg = &HA0
  146.                End If
  147.                .bCommandReg = &HEC
  148.                .bSectorCountReg = 1
  149.                .bSectorNumberReg = 1
  150.            End With
  151.        End With
  152.  
  153.        DeviceIoControl(hdh, DFP_RECEIVE_DRIVE_DATA, Bin, Len(Bin), Bout, Len(Bout), br, 0)
  154.  
  155.        S = ""
  156.        For Ix = hddfr To hddfr + hddln - 1 Step 2
  157.            If Bout.bBuffer(Ix + 1) = 0 Then Exit For
  158.            S &= Chr(Bout.bBuffer(Ix + 1))
  159.            If Bout.bBuffer(Ix) = 0 Then Exit For
  160.            S &= Chr(Bout.bBuffer(Ix))
  161.        Next Ix
  162.  
  163.        CloseHandle(hdh)
  164.        CmnGetHDData = Trim(S)
  165.    End Function
En línea

BlackZeroX
Wiki

Desconectado Desconectado

Mensajes: 3.158


I'Love...!¡.


Ver Perfil WWW
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #3 en: 3 Febrero 2021, 20:54 pm »

Puedes omitir el llamado de ZeroMemory* en VB .NET las variables ya se inicializan limpias* y no se ve que las uses entre la declaracion y la implementación de las mismas.

ZeroMemory
La función ZeroMemory llena un bloque de memoria con ceros.

Sintaxis
VOID ZeroMemory (
    PVOID Destination,  // puntero al bloque a llenar con ceros
    DWORD Length,       // tamaño, en bytes, del bloque a llenar
   );
Parámetros
Destination: puntero a la dirección de comienzo del bloque de memoria a llenar con ceros.

Length: especifica el tamaño, en bytes, del bloque de memoria a llenar con ceros.

Valor de retorno
Esta función no tiene valor de retorno.

Saludos.
En línea

The Dark Shadow is my passion.
Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.351


Ver Perfil
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #4 en: 3 Febrero 2021, 22:06 pm »

Alguien me pudiera aclarar como se puede obtener el número de serie de un disco físico, también el modelo del disco.

OJO!!! Que sea usando la API de Windows y en VB
.NET es muy completo, no necesitas usar APIs...

Si partes desde vb6, por ejemplo tiene sel objeto Scripting, que contiene la clase FilesystemObject, que a su vez contiene las clases Drives y Drive, para obtener datos de la unidad, si bien trae el SerialNumber (que los objetos Drive de .NET, no lo incorporan), tampoco trae el modelo de la unidad.

Aquí una sopa de código para rescatar algunos datos desde diversas fuentes en .NET...
Nota sin embargo que para usar el objeto Scripting tienes que agregar la referencia COM al proyecto, antes de instanciar y poder usarla...

Al final, accedemos al registro, para rescatar los nombres de las unidades conectadas internamente, las conectadas externamente ('removibles') se acceden desde la clave 'UsbStor' (incluídas las unidades ópticas). El ejemplo te vale para profundizar y modificar a tu gusto... como el registro es una base de datos fuertemente  jerarquizada es engorroso, para escribir código rápido pues debes recorrerlo iterativa o recursivamente si no te construyes alguna clase exprofeso para manejarlo con comodidad.

Código
  1. Imports Microsoft.Win32
  2.  
  3. Public Class Form1
  4.  
  5.    Private Enum DriveTypeScripting
  6.        DRIVE_TYPE_DESCONOCIDO = 0
  7.        DRIVE_TYPE_DESCONECTABLE = 1
  8.        DRIVE_TYPE_DISCODURO = 2
  9.        DRIVE_TYPE_REMOTO = 3
  10.        DRIVE_TYPE_OPTICA = 4
  11.        DRIVE_TYPE_RAMDISK = 5
  12.    End Enum
  13.    Private Function DriveTypeToString(ByVal DtS As DriveTypeScripting) As String
  14.        Select Case DtS
  15.            Case 0 : Return "Desconocido"
  16.            Case 1 : Return "Desconectable"
  17.            Case 2 : Return "Disco Duro"
  18.            Case 3 : Return "Unida de Red"
  19.            Case 4 : Return "Unidad óptica"
  20.            Case 5 : Return "Unidad de Memoria"
  21.                'Case else
  22.        End Select
  23.  
  24.        Return ""
  25.    End Function
  26.  
  27. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  28.        Dim dev As Devices.Computer
  29.        Dim info As String
  30.        Dim fso As New Scripting.FileSystemObject
  31.        Dim ds As Scripting.Drives
  32.        Dim key As RegistryKey, keyDrive As RegistryKey, keyIde As RegistryKey
  33.        Dim hk As RegistryHive
  34.        Dim rv As RegistryView
  35.  
  36.  
  37.  
  38.        ' Acceso desde el spacename IO
  39.        For Each d As IO.DriveInfo In IO.DriveInfo.GetDrives
  40.            With d
  41.                info = (.Name & vbNewLine & .DriveType.ToString)
  42.                If (.IsReady) Then info += (vbNewLine & .DriveFormat)
  43.                MessageBox.Show(info)
  44.                'info.
  45.            End With
  46.        Next
  47.  
  48.        ' Acceso desde el namespace IO y/o Win32.Devices
  49.        dev = New Devices.Computer
  50.        For Each d As IO.DriveInfo In dev.FileSystem.Drives
  51.            MessageBox.Show(d.Name)
  52.        Next
  53.  
  54.        ' Acceso a los datos de las unidades mediante el objeto FileSystemObject de la referencia Scripcing (que debe agregar desde COM).
  55.        Dim dtipo As Scripting.DriveTypeConst
  56.        Dim volLabel As String
  57.        ds = fso.Drives
  58.        For Each disk As Scripting.Drive In ds
  59.            With disk
  60.                dtipo = .DriveType
  61.                If (dtipo = DriveTypeScripting.DRIVE_TYPE_DISCODURO) Then
  62.                    volLabel = .VolumeName & vbNewLine
  63.                Else
  64.                    If .IsReady Then
  65.                        volLabel = .VolumeName & vbNewLine
  66.                    Else
  67.                        volLabel = ""
  68.                    End If
  69.                End If
  70.                info = (.DriveLetter & ":\" & vbNewLine & volLabel & DriveTypeToString(dtipo))
  71.                If .IsReady Then info += (vbNewLine & .SerialNumber)
  72.                MessageBox.Show(info)
  73.            End With
  74.        Next
  75.  
  76.        ' Acceso al registro para rescatar  el modelo de la unidad...
  77.        Dim subkeys() As String
  78.        hk = RegistryHive.LocalMachine
  79.        rv = RegistryView.Registry32
  80.        key = RegistryKey.OpenBaseKey(hk, rv)
  81.        Try
  82.            key = key.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Enum").OpenSubKey("IDE") ' "UsbStor"
  83.            subkeys = key.GetSubKeyNames
  84.            For k As Integer = 1 To key.SubKeyCount
  85.                keyIde = key.OpenSubKey(subkeys(k - 1))
  86.                keyDrive = keyIde.OpenSubKey(keyIde.GetSubKeyNames(0))
  87.                MsgBox(keyDrive.GetValue("FriendlyName"))
  88.                keyDrive.Close() : keyIde.Close()
  89.            Next
  90.        Catch ex As Exception ' no tienes permiso,
  91.            MessageBox.Show(ex.Message)
  92.        Finally
  93.            key.Close()
  94.        End Try
  95.    End Sub
  96. End Class
  97.  

Y ya desde ahí compón lo precises...

En línea

BlackZeroX
Wiki

Desconectado Desconectado

Mensajes: 3.158


I'Love...!¡.


Ver Perfil WWW
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #5 en: 4 Febrero 2021, 05:44 am »

Scripting.FileSystemObject... de hecho dicho objeto no parte de vb6 parte de vba, al final del día ya tiene varias formas de hacerlo

API Win32
Objetos COM (vba) en vb .NET

En cualquier caso según veo se debe ejecutar con privilegios de administrador, así que deberá agregar un MANIFEST para que escale permisos o que se ejecute con dicho permiso.

El código posteado por serapis (Solo parte del COM) por lo que se ve lista volúmenes lógicos y no físicos que para lo que se requiere es similar a este (VBS) crear un archivo en escritorio y con extensión "vbs" como ejecutar.vbs y pegar este código y darle doble click:

Código
  1. Dim fs, d, dc, s
  2. Set fs = CreateObject("Scripting.FileSystemObject")
  3. Set dc = fs.Drives
  4. For Each d in dc
  5.    s = s & d.DriveLetter & " tipo "  & d.DriveType & " serialNumber (Logico) "  & d.SerialNumber & vbNewLine
  6. Next
  7. MsgBox s
  8.  

Saludos.
« Última modificación: 4 Febrero 2021, 06:16 am por BlackZeroX (Astaroth) » En línea

The Dark Shadow is my passion.
Mr. NoBody

Desconectado Desconectado

Mensajes: 20


"You Take The Red Pill - You Stay In Wonderland"


Ver Perfil
Re: Obtener número de serie de un disco físico (no volumen lógico)
« Respuesta #6 en: 4 Febrero 2021, 21:01 pm »

Un tal ElektroStudios, programador enfocado en el desarrollo de aplicaciones de escritorio con VB.NET, publicó cierto programa / API open-source con fines educativos para demostrar cómo obtener todo tipo de información S.M.A.R.T de un disco, incluyendo por supuesto el número de serie y modelo:

S.M.A.R.T. Demo:
https://github.com/ElektroStudios/S.M.A.R.T.-Tool-for-.NET



Dicho esto, ten en cuenta que .NET Framework / VB.NET es en gran parte un gigantesco y optimizado wrapper de la API de Windows, así que en la mayoría de escenarios habituales de un programador con necesidades normales y corrientes no es necesario ni tampoco recomendable utilizar directamente la API de Windows, a menos que sea para escenarios y por motivos muy específicos, y siempre teniendo una base mínima de cococimiento sobre el uso de la librería de Windows y su implementación en .NET mediante Platform Invoke.

El código fuente del programa S.M.A.R.T. Demo se apoya en las funcionalidades de la infrastructura WMI (que hace uso interno de la API de Windows) para obtener toda la información.

Esto es lo más completo que vas a encontrar de forma open-source para .NET, la API es reutilizable así que es practicamente copiar y pegar código (todo el contenido de la carpeta 'DevCase') y ya estaría listo para darle uso en tu aplicación siguiendo y adaptando el ejemplo del programa...

Código
  1. Imports DevCase.Core.IO
  2.  
  3. For Each drive As HardDriveInfo In HardDriveInfo.GetDrives()
  4.    Dim sb As New StringBuilder()
  5.    sb.AppendLine($"{NameOf(drive.Name)}: {drive.Name}")
  6.    sb.AppendLine($"{NameOf(drive.VolumeLabel)}: {drive.VolumeLabel}")
  7.    sb.AppendLine($"{NameOf(drive.SerialNumber)}: {drive.SerialNumber}")
  8.  
  9.    Console.WriteLine(sb.ToString())
  10. Next drive

Citar
Name: C:\
VolumeLabel: Windows 10
SerialNumber: S4X6NJ0MC20670B

Pero también te digo que es bien fácil buscar en Google un simple código de pocas lineas para obtener el número de serie de un disco mediante WMI, ya sea en VB.NET y en C# también, y así no te complicas la vida usando toda una extensa API para lograr el mismo objetivo.

Saludos!
« Última modificación: 5 Febrero 2021, 12:19 pm por Mr. NoBody » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Obtener numero de serie del fabricante (usb)
Programación Visual Basic
Vampersy 1 15,229 Último mensaje 21 Enero 2009, 13:00 pm
por Fabricio
Obtener el numero de serie de una impresora
Scripting
Hekaly 1 9,282 Último mensaje 18 Septiembre 2012, 23:38 pm
por MCKSys Argentina
Obtener mayor número de una serie C++
Programación C/C++
Ingrid1997 1 1,853 Último mensaje 19 Octubre 2015, 05:52 am
por Seyro97
Cambiar número serie disco ?
Hardware
Rnovatis 2 9,529 Último mensaje 14 Octubre 2016, 20:05 pm
por Rnovatis
cambiar numero de serie de un disco duro.
Dudas Generales
julian@23 1 1,436 Último mensaje 6 Julio 2023, 04:20 am
por Machacador
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines