How to get a hard disk serial number? .NET version [C #]

xiaoxiao2021-03-06  50

The hard disk serial number is not equal to the volume name, and the latter is easy to get, but it will rewrite, unreliable after formatting the partition. Regrettably, many friends often can't distinguish this.

To get the physical serial number of the hard disk, you can pass WIN32_PHYSICALDIA.SERIALNUMBER. Unfortunately, the WINDOWS 98 / ME WMI does not support this class, and there will be exceptions when access.

Inspired by Lu Lin, we can also call API DeviceIOControl () from Ring3 to get the hard disk information directly from Ring3, without writing VXD or Driver. This problem is solved, I have packaged it, a large number of P / Invoke technology, a complete library. Supports Windows 98-2003.

It is very simple to use:

Harddiskinfo HDD = attapidevice.gethddinfo (0); // The first hard disk Console.Writeline ("Module Number: {0}", HDD.Modulenumber); console.writeline ("Serial Number: {0}", HDD.SerialNumber ); Console.writeline ("Firmware: {0}", HDD.Firmware); Console.Writeline ("Capacity: {0} M", HDD.capacity;

Here is all code:

Using system;

Using system.Runtime.InteropServices;

Using system.text;

Namespace Sunmast.hardware

{

[Serializable]

Public struct harddiskinfo

{

///

/// model

///

Public String Modulenumber;

///

/// Firmware version

///

Public String firmware;

///

/// serial number

///

Public String Serialnumber;

///

/// Capacity, in M ​​unit

///

Public uint capacity;

}

#Region Internal Structs

[Structlayout (layoutkind.sequential, pack = 1)]

Internal struct getversionoutparams

{

Public Byte Bversion;

Public Byte Brevision;

Public Byte Breserved;

Public BYTE BIDEDEVICEMAP;

Public uint fcapabilities;

[Marshalas (unmanagedtype.byvalarray, sizeconst = 4)]

Public uint [] dwreserved; // forfuture us.

}

[Structlayout (layoutkind.sequential, pack = 1)]

INTERNAL STRUCT IdeRegs

{

Public ByTe BfeaturesReg;

Public byte bsectorcountreg; public byte bsectornumberreg;

Public Byte Bcyllowreg;

Public Byte bcylhighreg;

Public Byte BDriveHeadReg;

Public Byte BCommandreg;

Public Byte Breserved;

}

[Structlayout (layoutkind.sequential, pack = 1)]

INTERNAL STRUCT Sendcmdinparams

{

Public uint cbuffersize;

Public ideregs IrdriveRIVEREGS;

Public Byte BDrivenumber;

[Marshalas (UnmanagedType.ByValarray, SizeConst = 3)]

Public Byte [] BRESERVED;

[Marshalas (unmanagedtype.byvalarray, sizeconst = 4)]

Public uint [] dwreserved;

Public Byte Bbuffer;

}

[Structlayout (layoutkind.sequential, pack = 1)]

Internal struct driverstatus

{

Public Byte BDriveRerror;

Public byte bidestatus;

[Marshalas (UnmanagedType.ByValarray, SizeConst = 2)]

Public Byte [] BRESERVED;

[Marshalas (UnmanagedType.ByValarray, SizeConst = 2)]

Public uint [] dwreserved;

}

[Structlayout (layoutkind.sequential, pack = 1)]

INTERNAL STRUCT Sendcmdoutparams

{

Public uint cbuffersize;

Public DriversTatus DriversTATUS DRIVERSTAS

Public IDsector bbuffer;

}

[StructLayout (layoutkind.sequential, pack = 1, size = 512)]

INTERNAL STRUCT IDSector

{

Public ushort wget wget;

Public ushort wnumcyls;

Public ushort wreserved;

Public ushort wnumheads;

Public ushort wbytespertrack;

Public ushort wbytespector;

Public Ushort WSectorspertrack;

[Marshalas (UnmanagedType.ByValarray, SizeConst = 3)]

Public ushort [] wvendorunique;

[Marshalas (unmanagedtype.byvalarray, sizeconst = 20)]

Public Byte [] sserialnumber;

Public ushort wbuffertype;

Public ushort wbuffers;

Public ushort weccsize;

[Marshalas (UnmanagedType.ByValarray, SIZECONST = 8)]]

Public Byte [] sfirmwarerev;

[Marshalas (UnmanagedType.ByValarray, SIZECONST = 40)]]

Public Byte [] Smodelnumber; Public Ushort WMOREVENDORUNIQUE

Public Ushort WDOUBLORDIO;

Public ushort wcapabilities;

Public Ushort Wreserved1;

Public ushort wpiotiming;

Public ushort wdmatiming;

Public Ushort WBS;

Public ushort wnumcurrentcyls;

Public ushort wnumcurrenthead;

Public ushort wnumcurrentsectorspertrack;

Public uint ulcurrentsectorcapacity;

Public Ushort WmultsectorStuff;

Public uint UltotaralddressAplansectors;

Public Ushort WSINGLEWORDDMA;

Public ushort wmultiworddma;

[Marshalas (unmanagedtype.byvalarray, sizeconst = 128)]]

Public Byte [] BRESERVED;

}

#ndregion

///

/// ATAPI drive related

///

Public Class Atapidevice

{

#Region DllImport

[DLLIMPORT ("kernel32.dll", setLastError = true)]

Static Extern Int CloseHandle (INTPTR HOBJECT);

[DLLIMPORT ("kernel32.dll", setLastError = true)]

Static Extern INTPTR CREATEFILE

String lpfilename,

Uint dwdesiredAccess,

Uint dwsharemode,

INTPTR LPSECurityAttributes,

uint dwcreationdisposition,

Uint dwflagsandattributes,

INTPTR HTEMPLATEFILE

[DLLIMPORT ("kernel32.dll")]]]]

Static Extern Int De deviceiocontrol

INTPTR HDEVICE,

Uint dwiocontrolcode,

INTPTR LPINBUFFER,

Uint Ninbuffersize,

Ref getversionoutparams lpoutbuffer,

Uint NoutBuffersize,

Ref uint lpbytesreturned,

[OUT] INTPTR LPOVERLAPPED);

[DLLIMPORT ("kernel32.dll")]]]]

Static Extern Int De deviceiocontrol

INTPTR HDEVICE,

Uint dwiocontrolcode,

Ref sendcmdinparams lpinbuffer,

Uint Ninbuffersize,

Ref sendcmdoutparams LPOUTBUFFER,

Uint NoutBuffersize,

Ref uint lpbytesreturned,

[OUT] INTPTR LPOVERLAPPED);

Const uint DFP_GET_VERSION = 0x00074080;

Const uint DFP_SEND_DRIVE_COMMAND = 0x0007c084;

Const uint DFP_RECEIVE_DRIVE_DATA = 0x0007c088; Const uint generic_read = 0x80000000;

Const uint generic_write = 0x40000000;

Const uint file_share_read = 0x00000001;

Const uint file_share_write = 0x00000002;

Const uint create_new = 1;

Const uint open_existing = 3;

#ndregion

#Region gethddinfo

///

/// Get hard disk information

///

/// Hard disk serial number

/// Hard disk information

///

/// Refer to LU0 articles: http://lu0s1.3322.org/app/2k1103.html

/// by Sunmast for Everyone

/// THANKS LU0 for His Great Works

/// In Windows 98 / ME, S.m.a.r.t does not have a default, copy smartvsd.vxd to the% system% / iOSubsys directory.

/// Under Windows 2000/2003, you need the permissions of the Administrators group.

///

///

/// atapidevice.gethddinfo ()

///

Public Static HardDiskinfo gethddinfo (Byte DriveIndex)

{

Switch (Environment.OSversion.Platform)

{

Case PlatformID.WIN32WINDOWS:

Return gethDINFO9X (DriveIndex);

Case PlatformID.WIN32NT:

Return gethDINFONT (DRIVEINDEX);

Case PlatformID.WIN32S:

Throw New NotSupportedException ("Win32S is Not Supported.");

Case PlatformID.wince:

Throw new NotSupportedException ("Wince IS Not Supported.");

DEFAULT:

Throw New NotSupportedException ("Unknown Platform.");

}

}

#Region gethddinfo9x

Private static harddiskinfo gethddinfo9x (byte driveIndex)

{

GetversionOutparams Vers = new getversionoutparams ();

Sendcmdinparams INPARAM = New Sendcmdinparams ();

Sendcmdoutparams Outparam = new sendcmdoutparams ();

uint bytesreturned = 0;

INTPTR HDEVICE = CREATEFILE

@ "//./ SmartVSD",

0,

0,

INTPTR.ZERO,

CREATE_NEW, 0,

INTPTR.ZERO);

IF (HDevice == INTPTR.ZERO)

{

Throw New Exception ("Open SmartVsd.vxd Failed.");

}

IF (0 == DeviceioControl

HDevice,

DFP_GET_VERSION,

INTPTR.ZERO,

0,

Ref Vers,

(uint) Marshal.Sizeof (VERS),

Ref bytesreturned,

INTPTR.ZERO))

{

CloseHandle (HDEvice);

Throw New Exception ("DeviceIocontrol Failed: DFP_GET_VERSION");

}

// if Ide Identify Command Not Supported, Fails

IF (0 == (VERS.FCAPABILITIES & 1))

{

CloseHandle (HDEvice);

Throw New Exception ("Error: Ide Identify Command Not Supported.");

}

IF (0! = (DriveIndex & 1))

{

INPARAM.IRDRIVEREGS.BDRIVEHEADREG = 0xB0;

}

Else

{

INPARAM.IRDRIVEREGS.BDRIVEHEADREG = 0xA0;

}

IF (0! = (VERS.FCAPABILITIES & (16 >> DriveIndex)))

{

// We don't detect a atapi device.

CloseHandle (HDEvice);

Throw new Exception (String.Format ("Drive {0} is a atapi device, we don't detect it", driveIndex 1);

}

Else

{

INPARAM.IRDRIVEREGS.BCOMMANDREG = 0XEC;

}

INPARAM.BDRIVENUMBER = DriveIndex;

INPARAM.IRDRIVEREGS.BSECTORCOUNTREG = 1;

INPARAM.IRDRIVEREGS.BSECTORNUMBERREG = 1;

INPARAM.CBUFFERSIZE = 512;

IF (0 == DeviceioControl

HDevice,

DFP_RECEIVE_DRIVE_DATA,

Ref INPARAM,

(uint) Marshal.Sizeof (Inparam),

Ref outparam,

(uint) Marshal.Sizeof (Outparam),

Ref bytesreturned,

INTPTR.ZERO))

{

CloseHandle (HDEvice);

Throw New Exception ("Deviceiocontrol Failed: DFP_RECEIVE_DRIVE_DATA");

}

CloseHandle (HDEvice);

Return Getharddiskinfo (Outparam.bbuffer);

}

#ndregion

#Region gethddinfont

Private static harddiskinfo gethdinfont (byte driveIndex)

{

GetversionOutparams Vers = new getversionoutparams ();

Sendcmdinparams INPARAM = new sendcmdinparams (); sendcmdoutparams outparam = new sendcmdoutparams ();

uint bytesreturned = 0;

// We start in nt / win2000

INTPTR HDEVICE = CREATEFILE

String.format (@ "//./ PhysicalDrive {0}", DriveIndex,

Generic_read | generic_write,

File_share_read | file_share_write,

INTPTR.ZERO,

Open_EXISTING,

0,

INTPTR.ZERO);

IF (HDevice == INTPTR.ZERO)

{

Throw new Exception ("CreateFile Faild.");

}

IF (0 == DeviceioControl

HDevice,

DFP_GET_VERSION,

INTPTR.ZERO,

0,

Ref Vers,

(uint) Marshal.Sizeof (VERS),

Ref bytesreturned,

INTPTR.ZERO))

{

CloseHandle (HDEvice);

Throw new Exception (String.Format ("Drive {0} May Not Exists", DriveIndex 1)

}

// if Ide Identify Command Not Supported, Fails

IF (0 == (VERS.FCAPABILITIES & 1))

{

CloseHandle (HDEvice);

Throw New Exception ("Error: Ide Identify Command Not Supported.");

}

// Identify The Ide Drives

IF (0! = (DriveIndex & 1))

{

INPARAM.IRDRIVEREGS.BDRIVEHEADREG = 0xB0;

}

Else

{

INPARAM.IRDRIVEREGS.BDRIVEHEADREG = 0xA0;

}

IF (0! = (VERS.FCAPABILITIES & (16 >> DriveIndex)))

{

// We don't detect a atapi device.

CloseHandle (HDEvice);

Throw new Exception (String.Format ("Drive {0} is a atapi device, we don't detect it.", driveIndex 1);

}

Else

{

INPARAM.IRDRIVEREGS.BCOMMANDREG = 0XEC;

}

INPARAM.BDRIVENUMBER = DriveIndex;

INPARAM.IRDRIVEREGS.BSECTORCOUNTREG = 1;

INPARAM.IRDRIVEREGS.BSECTORNUMBERREG = 1;

INPARAM.CBUFFERSIZE = 512;

IF (0 == DeviceioControl

HDevice,

DFP_RECEIVE_DRIVE_DATA,

Ref INPARAM,

(uint) Marshal.Sizeof (Inparam),

Ref outparam,

(uint) Marshal.Sizeof (Outparam), Ref bytesReturned,

INTPTR.ZERO))

{

CloseHandle (HDEvice);

Throw New Exception ("Deviceiocontrol Failed: DFP_RECEIVE_DRIVE_DATA");

}

CloseHandle (HDEvice);

Return Getharddiskinfo (Outparam.bbuffer);

}

#ndregion

Private static harddiskinfo getharddiskinfo (idsector pHDINFO)

{

Harddiskinfo HDDINFO = New HardDiskinfo ();

Changebyteorder (pHDINFO.SMODELNUMBER);

HDDINFO.MODULENUMBER = Encoding.ASCII.GetString (phdinfo.smodelnumber) .trim ();

Changebyteorder (phDinfo.sfirmwarerev);

HDDINFO.FIRMware = encoding.ascii.getstring (phdinfo.sfirmwarerev) .trim ();

Changebyteorder (pHDINFO.SSERIALNUMBER);

HDDINFO.SERIALNUMBER = Encoding.ascii.getstring (phdinfo.sserialnumber) .trim ();

HDDInfo.capacity = phDinfo.ulttotaralddressables / 2/1024;

Return HDDINFO;

}

Private static void changebyteorder (byte [] charrray)

{

BYTE TEMP;

For (int i = 0; i

{

Temp = charRay [i];

Chararray [I] = Chararray [i 1];

Chararray [i 1] = TEMP;

}

}

#ndregion

}

}

Note:

In Windows 98 / ME, S.M.R.T does not have a default installation, copy smartvsd.vxd to the% system% / iosubsys directory. Under Windows 2000/2003, you need the permissions of the Administrators group. Don't try on the machine equipped with a SCSI hard drive because the SCSI hard drive does not exist at all.

转载请注明原文地址:https://www.9cbs.com/read-83279.html

New Post(0)