// Initialize the output buffer to the size of a Win32 DEVICE_ID structure
byte[] outbuff = new byte[20];
Int32 dwOutBytes;
bool done = false;
Int32 nBuffSize = outbuff.Length;
// Set DEVICEID.dwSize to size of buffer. Some platforms look at
// this field rather than the nOutBufSize param of KernelIoControl
// when determining if the buffer is large enough.
//
BitConverter.GetBytes(nBuffSize).CopyTo(outbuff, 0);
dwOutBytes = 0;
// Loop until the device ID is retrieved or an error occurs
while (!done)
{
if (KernelIoControl(IOCTL_HAL_GET_DEVICEID, IntPtr.Zero, 0, outbuff, nBuffSize, ref dwOutBytes))
{
done = true;
}
else
{
int error = Marshal.GetLastWin32Error();
switch (error)
{
case ERROR_NOT_SUPPORTED:
throw new NotSupportedException("IOCTL_HAL_GET_DEVICEID is not supported on this device", new Win32Exception(error));
case ERROR_INSUFFICIENT_BUFFER:
// The buffer wasn't big enough for the data. The
// required size is in the first 4 bytes of the output
// buffer (DEVICE_ID.dwSize).
nBuffSize = BitConverter.ToInt32(outbuff, 0);
outbuff = new byte[nBuffSize];
// Set DEVICEID.dwSize to size of buffer. Some
// platforms look at this field rather than the
// nOutBufSize param of KernelIoControl when
// determining if the buffer is large enough.
//
BitConverter.GetBytes(nBuffSize).CopyTo(outbuff, 0);
break;
default:
throw new Win32Exception(error, "Unexpected error");
}
}
}
忘记写引用了
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.Cryptography;