public bool USBSCSIWrite(byte[] pCDB, int nCDBLen, byte[] pData, uint nLength, uint nTimeOut) { try { bool status = false; ScsiPassThroughDirectWithBuffers sptdwb; int length = 0; uint TransLen; uint returned = 0; IntPtr w_pBuf; IntPtr w_pData; if (m_hHandle.IsInvalid) { return(false); } TransLen = nLength; w_pData = Marshal.AllocHGlobal((int)nLength); Marshal.Copy(pData, 0, w_pData, (int)nLength); sptdwb = new ScsiPassThroughDirectWithBuffers(1, 0, 0, 6 /*CDB6GENERIC_LENGTH*/, TransLen); sptdwb.spt.DataIn = 0; //SCSI_IOCTL_DATA_OUT sptdwb.spt.TimeOutValue = nTimeOut; sptdwb.spt.DataBuffer = w_pData; Array.Copy(pCDB, sptdwb.spt.Cdb, nCDBLen); length = Marshal.SizeOf(sptdwb); w_pBuf = Marshal.AllocHGlobal(length); Marshal.StructureToPtr(sptdwb, w_pBuf, false); status = DeviceIoControl(m_hHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT, w_pBuf, (uint)length, w_pBuf, (uint)length, ref returned, IntPtr.Zero); Marshal.PtrToStructure(w_pBuf, sptdwb); if (status == false) { length = Marshal.GetLastWin32Error(); } Marshal.FreeHGlobal(w_pBuf); Marshal.FreeHGlobal(w_pData); return(status); } catch { return(false); } }
public bool CallDeviceIoControl(SafeFileHandle volume, ref byte[] data, byte command, byte LBA, byte secCount, byte dataInOut) { ScsiPassThroughDirectWithBuffers sptdwb = new ScsiPassThroughDirectWithBuffers(); sptdwb.Init(command, LBA, secCount, dataInOut); IntPtr input = IntPtr.Zero; IntPtr unmanagedPointer = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, unmanagedPointer, data.Length); sptdwb.spt.DataBuffer = unmanagedPointer; uint length = (uint)Marshal.SizeOf(typeof(ScsiPassThroughDirectWithBuffers)); uint bytesreturned = 0; uint ioctl_scsi_base = 0x00000004; uint function = 0x0405; uint method = 0; uint access = 0x0001 | 0x0002; uint ioControlCode = CTL_CODE(ioctl_scsi_base, function, method, access); bool status = false; IntPtr ptr = Marshal.AllocHGlobal((int)length); Marshal.StructureToPtr(sptdwb, ptr, false); try { status = DeviceIoControl(volume, ioControlCode, ptr, length, ptr, length, out bytesreturned, IntPtr.Zero); if (status) { if (dataInOut == 1) { Marshal.Copy(sptdwb.spt.DataBuffer, data, 0, data.Length); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Marshal.FreeHGlobal(unmanagedPointer); } return status; }