Error calling HidP_GetButtonCaps routine from C# - interop

I have spent hours and still can't understand why calling the HidP_GetButtonCaps routine (from hid.dll) fails when using Interop in C#.
I am listing devices and trying to get ButtonCaps and so on. But when calling HidP_GetButtonCaps (or HidP_GetValueCaps) the extern function returns an HIDP_STATUS_INVALID_REPORT_TYPE error. And I just don't get it... the report type parameter in this routine is a enum value, how can it fails ???
Here is some code extract. I won't put everything because it is long. Of course if more details need to be put, I'll add it.
There are comments in the code "//REMARK", here is the remarks content:
- Remark 1 : the hidDevice object parameter comes from another method. I know the content of the "DevicePath", "preparsedData" and "ButtonCaps" fields are correct when checking things in debugging mode.
- Remark 2 : here is where I have the problem. I've tried 3 different ways for the argument: with a HIDP_REPORT_TYPE object, directly with HIDP_REPORT_TYPE.HidP_Input or "0", and it does not make any difference...
Thanks so much for your help.
Structures, constants, enum... :
public enum HIDP_REPORT_TYPE : ushort
{
HidP_Input,
HidP_Output,
HidP_Feature
}
public struct ButtonCapsRange
{
public ushort UsageMin;
public ushort UsageMax;
public ushort StringMin;
public ushort StringMax;
public ushort DesignatorMin;
public ushort DesignatorMax;
public ushort DataIndexMin;
public ushort DataIndexMax;
}
public struct ButtonCapsNotRange
{
public ushort Usage;
public ushort Reserved1;
public ushort StringIndex;
public ushort Reserved2;
public ushort DesignatorIndex;
public ushort Reserved3;
public ushort DataIndex;
public ushort Reserved4;
}
[StructLayout(LayoutKind.Explicit)]
public struct HIDP_BUTTON_CAPS
{
[FieldOffset(0)]
public ushort UsagePage;
[FieldOffset(2)]
public byte ReportID;
[FieldOffset(3)]
public bool IsAlias;
[FieldOffset(4)]
public ushort BitField;
[FieldOffset(6)]
public ushort LinkCollection;
[FieldOffset(8)]
public ushort LinkUsage;
[FieldOffset(10)]
public ushort LinkUsagePage;
[FieldOffset(12)]
public bool IsRange;
[FieldOffset(13)]
public bool IsStringRange;
[FieldOffset(14)]
public bool IsDesignatorRange;
[FieldOffset(15)]
public bool IsAbsolute;
[FieldOffset(16)]
public uint[] Reserved;
[FieldOffset(16 + 10 * 4)]
public ButtonCapsRange Range;
[FieldOffset(16 + 10 * 4)]
public ButtonCapsNotRange NotRange;
}
public struct HID_DEVICE
{
public String DevicePath;
public IntPtr pHidDevice; // A file handle to the hid device.
public bool OpenedForRead;
public bool OpenedForWrite;
public bool OpenedOverlapped;
public bool OpenedExclusive;
public IntPtr Ppd; // The opaque parser info describing this device
public HIDP_CAPS Caps; // The Capabilities of this hid device.
public HIDD_ATTRIBUTES Attributes;
public byte[] pInputReportBuffer;
public HID_DATA[] InputData; // array of hid data structures
public ulong InputDataLength; // Num elements in this array.
public HIDP_BUTTON_CAPS[] pInputButtonCaps;
public HIDP_VALUE_CAPS[] pInputValueCaps;
public byte[] pOutputReportBuffer;
public HID_DATA[] pOutputData;
public ulong OutputDataLength;
public HIDP_BUTTON_CAPS[] pOutputButtonCaps;
public HIDP_VALUE_CAPS[] pOutputValueCaps;
public byte[] pFeatureReportBuffer;
public HID_DATA[] pFeatureData;
public ulong FeatureDataLength;
public HIDP_BUTTON_CAPS[] pFeatureButtonCaps;
public HIDP_VALUE_CAPS[] pFeatureValueCaps;
}
external methods:
[DllImport("hid.dll", SetLastError = true)]
[SecurityPermission(SecurityAction.Assert, Unrestricted = true)]
static extern int HidP_GetButtonCaps([MarshalAs(UnmanagedType.U2)] HIDP_REPORT_TYPE ReportType, ref HIDP_BUTTON_CAPS[] ButtonCaps, ref ushort ButtonCapsLength, IntPtr PreparsedData);
Call of the method:
private static bool FillDeviceInfo(ref HID_DEVICE hidDevice)
{
//REMARK 1
ulong numValues;
ushort numCaps;
HIDP_BUTTON_CAPS[] buttonCaps;
HIDP_VALUE_CAPS[] valueCaps;
HID_DATA[] data;
ulong i;
ushort usage;
uint dataIdx;
hidDevice.pInputReportBuffer = new byte[hidDevice.Caps.InputReportByteLength];
buttonCaps = new HIDP_BUTTON_CAPS[hidDevice.Caps.NumberInputButtonCaps];
//for(int a=0;a<buttonCaps.Length ;a++)
// buttonCaps[a].Reserved = new uint[10];
hidDevice.pInputButtonCaps = buttonCaps;
valueCaps = new HIDP_VALUE_CAPS[hidDevice.Caps.NumberInputValueCaps];
hidDevice.pInputValueCaps = valueCaps;
numCaps = hidDevice.Caps.NumberInputButtonCaps;
if (numCaps > 0)
{
//REMARK 2
HIDP_REPORT_TYPE reportType = HIDP_REPORT_TYPE.HidP_Input;
int val = (HidP_GetButtonCaps(reportType, ref buttonCaps, ref numCaps, hidDevice.Ppd));
if (HIDP_STATUS_SUCCESS != val)
{
return false;
}
}
//other stuff and retur true at end
}

OK found the problem... stupid mistake as often.
I solved the problem of the "invalid report type" error by removing the ":ushort" in the enum definition. I thought it was a 2 bytes data in C, but it was a 4 bytes data.
Also, there was a problem with working with tables made in managed memory in HidP_GetButtonCaps.
Instead of using a array of HIDP_BUTTON_CAPS (initialized in managed memory) in HidP_GetButtonCaps, I use a IntPtr refering to an unmanaged memory zone.

I was getting the same kind of exception. I think there's a problem in the CLR trying to automatically marshall data to a struct with a union. Maybe. I wrote my own unpacking method and that seems to have fixed the problem.
public static HidpButtonCaps FromByteArray(byte[] bytes, int offset)
{
var hbc = new HidpButtonCaps()
{
UsagePage = (ushort)(((ushort)bytes[offset+1] << 8) | (ushort)(bytes[offset])),
ReportID = bytes[offset + 2] > 0 ? true : false,
IsAlias = bytes[offset + 3] > 0 ? true : false,
BitField = (ushort)(((ushort)bytes[offset + 5] << 8) | (ushort)(bytes[offset + 4])),
LinkCollection = (ushort)(((ushort)bytes[offset + 7] << 8) | (ushort)(bytes[offset + 6])),
LinkUsage = (ushort)(((ushort)bytes[offset + 9] << 8) | (ushort)(bytes[offset + 8])),
IsRange = bytes[offset + 10] > 0 ? true : false,
IsStringRange = bytes[offset + 11] > 0 ? true : false,
IsDesignatorRange = bytes[offset + 12] > 0 ? true : false,
IsAbsolute = bytes[offset + 13] > 0 ? true : false,
// skip reserved
Range = new HidpButtonCapsRange()
{
UsageMin = (ushort)(((ushort)bytes[offset + 57] << 8) | (ushort)(bytes[offset + 56])),
UsageMax = (ushort)(((ushort)bytes[offset + 59] << 8) | (ushort)(bytes[offset + 58])),
StringMin = (ushort)(((ushort)bytes[offset + 61] << 8) | (ushort)(bytes[offset + 61])),
StringMax = (ushort)(((ushort)bytes[offset + 63] << 8) | (ushort)(bytes[offset + 62])),
DesignatorMin = (ushort)(((ushort)bytes[offset + 65] << 8) | (ushort)(bytes[offset + 64])),
DesignatorMax = (ushort)(((ushort)bytes[offset + 67] << 8) | (ushort)(bytes[offset + 66])),
DataIndexMin = (ushort)(((ushort)bytes[offset + 69] << 8) | (ushort)(bytes[offset + 68])),
DataIndexMax = (ushort)(((ushort)bytes[offset + 71] << 8) | (ushort)(bytes[offset + 70])),
}
};
return hbc;
}
I use it like this
dwSize = hidpcaps.NumberInputButtonCaps;
var bytelength = Marshal.SizeOf(typeof(HidpButtonCaps)) * (int)dwSize;
HidpButtonCaps[] buttonCaps = new HidpButtonCaps[(int)dwSize];
var pbuttoncaps = Marshal.AllocHGlobal(bytelength);
hidpstatus = (HidpStatus)HidP_GetButtonCaps(HidpReportType.HidP_Input, pbuttoncaps, ref dwSize, pPreparsedData);
if (hidpstatus != HidpStatus.HIDP_STATUS_SUCCESS)
{
throw new Win32Exception($"HidP_GetButtonCaps: {hidpstatus.ToString()}");
}
var buttonCapBytes = new byte[bytelength];
Marshal.Copy(pbuttoncaps, buttonCapBytes, 0, bytelength);
for (int i=0; i<(int)hidpcaps.NumberInputButtonCaps; i++)
{
buttonCaps[i] = HidpButtonCaps.FromByteArray(buttonCapBytes, i * Marshal.SizeOf(typeof(HidpButtonCaps)));
}

Related

Windows Storage Management API - VDS (Virtual Disk Service) Uninstall Disk Equivalent method

Since VDS is being deprecated and the Windows Storage Management API is replacing it - are there any WMI, IOCTL, DeviceIoControl or Windows Storage Management API methods that are equivalent to the VDS method "UninstallDisks"?
I'm not able to find any other method of doing what the VDS method "UninstallDisks" does.
Any help would be appreciated.
Figured it out myself with a combination of other contributors code.
Reference:
Win32 API function to programmatically enable/disable device
Main codebase below:
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace WindowsStorageManagementAPI.Devices
{
public class DeviceInfoData
{
public int Size { get; set; }
public Guid ClassGuid { get; set; }
public int DevInst { get; set; }
public IntPtr Reserved { get; set; }
}
public class SetupApiWrapper
{
private const string SetupAPI = "setupapi.dll";
private const string NewDevLib = "Newdev.dll";
#region NATIVE ENUMS
[Flags()]
private enum SetupDiGetClassDevsFlags
{
Default = 1,
Present = 2,
AllClasses = (int)0x04,
Profile = 8,
DeviceInterface = (int)0x10
}
private enum DiFunction
{
SelectDevice = 1,
InstallDevice = 2,
AssignResources = 3,
Properties = 4,
Remove = 5,
FirstTimeSetup = 6,
FoundDevice = 7,
SelectClassDrivers = 8,
ValidateClassDrivers = 9,
InstallClassDrivers = (int)0xa,
CalcDiskSpace = (int)0xb,
DestroyPrivateData = (int)0xc,
ValidateDriver = (int)0xd,
Detect = (int)0xf,
InstallWizard = (int)0x10,
DestroyWizardData = (int)0x11,
PropertyChange = (int)0x12,
EnableClass = (int)0x13,
DetectVerify = (int)0x14,
InstallDeviceFiles = (int)0x15,
UnRemove = (int)0x16,
SelectBestCompatDrv = (int)0x17,
AllowInstall = (int)0x18,
RegisterDevice = (int)0x19,
NewDeviceWizardPreSelect = (int)0x1a,
NewDeviceWizardSelect = (int)0x1b,
NewDeviceWizardPreAnalyze = (int)0x1c,
NewDeviceWizardPostAnalyze = (int)0x1d,
NewDeviceWizardFinishInstall = (int)0x1e,
Unused1 = (int)0x1f,
InstallInterfaces = (int)0x20,
DetectCancel = (int)0x21,
RegisterCoInstallers = (int)0x22,
AddPropertyPageAdvanced = (int)0x23,
AddPropertyPageBasic = (int)0x24,
Reserved1 = (int)0x25,
Troubleshooter = (int)0x26,
PowerMessageWake = (int)0x27,
AddRemotePropertyPageAdvanced = (int)0x28,
UpdateDriverUI = (int)0x29,
Reserved2 = (int)0x30
}
private enum StateChangeAction
{
Enable = 1,
Disable = 2,
PropChange = 3,
Start = 4,
Stop = 5
}
[Flags()]
private enum Scope
{
Global = 1,
ConfigSpecific = 2,
ConfigGeneral = 4
}
private enum SetupApiError
{
NoAssociatedClass = unchecked((int)0xe0000200),
ClassMismatch = unchecked((int)0xe0000201),
DuplicateFound = unchecked((int)0xe0000202),
NoDriverSelected = unchecked((int)0xe0000203),
KeyDoesNotExist = unchecked((int)0xe0000204),
InvalidDevinstName = unchecked((int)0xe0000205),
InvalidClass = unchecked((int)0xe0000206),
DevinstAlreadyExists = unchecked((int)0xe0000207),
DevinfoNotRegistered = unchecked((int)0xe0000208),
InvalidRegProperty = unchecked((int)0xe0000209),
NoInf = unchecked((int)0xe000020a),
NoSuchHDevinst = unchecked((int)0xe000020b),
CantLoadClassIcon = unchecked((int)0xe000020c),
InvalidClassInstaller = unchecked((int)0xe000020d),
DiDoDefault = unchecked((int)0xe000020e),
DiNoFileCopy = unchecked((int)0xe000020f),
InvalidHwProfile = unchecked((int)0xe0000210),
NoDeviceSelected = unchecked((int)0xe0000211),
DevinfolistLocked = unchecked((int)0xe0000212),
DevinfodataLocked = unchecked((int)0xe0000213),
DiBadPath = unchecked((int)0xe0000214),
NoClassInstallParams = unchecked((int)0xe0000215),
FileQueueLocked = unchecked((int)0xe0000216),
BadServiceInstallSect = unchecked((int)0xe0000217),
NoClassDriverList = unchecked((int)0xe0000218),
NoAssociatedService = unchecked((int)0xe0000219),
NoDefaultDeviceInterface = unchecked((int)0xe000021a),
DeviceInterfaceActive = unchecked((int)0xe000021b),
DeviceInterfaceRemoved = unchecked((int)0xe000021c),
BadInterfaceInstallSect = unchecked((int)0xe000021d),
NoSuchInterfaceClass = unchecked((int)0xe000021e),
InvalidReferenceString = unchecked((int)0xe000021f),
InvalidMachineName = unchecked((int)0xe0000220),
RemoteCommFailure = unchecked((int)0xe0000221),
MachineUnavailable = unchecked((int)0xe0000222),
NoConfigMgrServices = unchecked((int)0xe0000223),
InvalidPropPageProvider = unchecked((int)0xe0000224),
NoSuchDeviceInterface = unchecked((int)0xe0000225),
DiPostProcessingRequired = unchecked((int)0xe0000226),
InvalidCOInstaller = unchecked((int)0xe0000227),
NoCompatDrivers = unchecked((int)0xe0000228),
NoDeviceIcon = unchecked((int)0xe0000229),
InvalidInfLogConfig = unchecked((int)0xe000022a),
DiDontInstall = unchecked((int)0xe000022b),
InvalidFilterDriver = unchecked((int)0xe000022c),
NonWindowsNTDriver = unchecked((int)0xe000022d),
NonWindowsDriver = unchecked((int)0xe000022e),
NoCatalogForOemInf = unchecked((int)0xe000022f),
DevInstallQueueNonNative = unchecked((int)0xe0000230),
NotDisableable = unchecked((int)0xe0000231),
CantRemoveDevinst = unchecked((int)0xe0000232),
InvalidTarget = unchecked((int)0xe0000233),
DriverNonNative = unchecked((int)0xe0000234),
InWow64 = unchecked((int)0xe0000235),
SetSystemRestorePoint = unchecked((int)0xe0000236),
IncorrectlyCopiedInf = unchecked((int)0xe0000237),
SceDisabled = unchecked((int)0xe0000238),
UnknownException = unchecked((int)0xe0000239),
PnpRegistryError = unchecked((int)0xe000023a),
RemoteRequestUnsupported = unchecked((int)0xe000023b),
NotAnInstalledOemInf = unchecked((int)0xe000023c),
InfInUseByDevices = unchecked((int)0xe000023d),
DiFunctionObsolete = unchecked((int)0xe000023e),
NoAuthenticodeCatalog = unchecked((int)0xe000023f),
AuthenticodeDisallowed = unchecked((int)0xe0000240),
AuthenticodeTrustedPublisher = unchecked((int)0xe0000241),
AuthenticodeTrustNotEstablished = unchecked((int)0xe0000242),
AuthenticodePublisherNotTrusted = unchecked((int)0xe0000243),
SignatureOSAttributeMismatch = unchecked((int)0xe0000244),
OnlyValidateViaAuthenticode = unchecked((int)0xe0000245),
NoMoreItems = unchecked((int)0xe0000259),
ElementNotFound = unchecked((int)0xe0001168),
InvalidData = unchecked((int)0xe0000013),
}
#endregion
#region NATIVE STRUCTS
[StructLayout(LayoutKind.Sequential)]
private struct DeviceInfoDataNative
{
public int Size;
public Guid ClassGuid;
public int DeviceInstance;
public IntPtr Reserved;
}
[StructLayout(LayoutKind.Sequential)]
private struct ClassInstallHeader
{
public int Size;
public DiFunction InstallFunction;
}
[StructLayout(LayoutKind.Sequential)]
private struct PropertyChangeParameters
{
public ClassInstallHeader ClassInstallHeader;
public StateChangeAction StateChange;
public Scope Scope;
public int HwProfile;
}
[StructLayout(LayoutKind.Sequential)]
private struct RemoveDeviceParameters
{
public ClassInstallHeader ClassInstallHeader;
public Scope Scope;
public int HwProfile;
}
[StructLayout(LayoutKind.Sequential)]
private struct DevicePropertyKey
{
public Guid fmtId;
public int pId;
// from devpkey.h
public static readonly DevicePropertyKey Device_Parent = new DevicePropertyKey { fmtId = new Guid("{4340A6C5-93FA-4706-972C-7B648008A5A7}"), pId = 8 };
public static readonly DevicePropertyKey Device_Children = new DevicePropertyKey { fmtId = new Guid("{4340A6C5-93FA-4706-972C-7B648008A5A7}"), pId = 9 };
}
#endregion
#region P/INVOKE
[SuppressUnmanagedCodeSecurity()]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport(SetupAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
[DllImport(SetupAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetupDiCallClassInstaller(DiFunction installFunction, SafeDeviceInfoSetHandle deviceInfoSet, [In()] ref DeviceInfoDataNative deviceInfoData);
[DllImport(SetupAPI, SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(SafeDeviceInfoSetHandle DeviceInfoSet, int MemberIndex, ref DeviceInfoDataNative DeviceInfoData);
[DllImport(SetupAPI, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeDeviceInfoSetHandle SetupDiGetClassDevs(ref Guid ClassGuid, [MarshalAs(UnmanagedType.LPWStr)] string Enumerator, IntPtr HwndParent, SetupDiGetClassDevsFlags Flags);
[DllImport(SetupAPI, SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetupDiGetDeviceInstanceId(IntPtr deviceInfoSet, ref DeviceInfoDataNative did, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder DeviceInstanceId, int DeviceInstanceIdSize, out int RequiredSize);
[DllImport(SetupAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetupDiSetClassInstallParams(SafeDeviceInfoSetHandle deviceInfoSet, [In()] ref DeviceInfoDataNative deviceInfoData, [In()] ref RemoveDeviceParameters classInstallParams, int classInstallParamsSize);
[DllImport("Newdev.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DiUninstallDevice(IntPtr hwnd, [In()] SafeDeviceInfoSetHandle deviceInfoSet, [In()] ref DeviceInfoDataNative deviceInfoData, [In()] int flags, out bool NeedReboot);
[DllImport(SetupAPI, SetLastError = true, EntryPoint = "SetupDiGetDevicePropertyW")]
private static extern bool SetupDiGetDeviceProperty(SafeDeviceInfoSetHandle deviceInfoSet, ref DeviceInfoDataNative DeviceInfoData, ref DevicePropertyKey propertyKey, out int propertyType, IntPtr propertyBuffer, int propertyBufferSize, out int requiredSize, int flags);
#endregion
private class SafeDeviceInfoSetHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeDeviceInfoSetHandle() : base(true)
{
}
protected override bool ReleaseHandle()
{
return SetupDiDestroyDeviceInfoList(this.handle);
}
}
private static DeviceInfoDataNative GetDeviceInfoData(SafeDeviceInfoSetHandle handle)
{
DeviceInfoDataNative _data = new DeviceInfoDataNative();
_data.Size = Marshal.SizeOf(_data);
if (!SetupDiEnumDeviceInfo(handle, 0, ref _data))
{
int error = Marshal.GetLastWin32Error();
if (error == (int)SetupApiError.NoMoreItems)
return _data;
throw new Win32Exception(error);
}
return _data;
}
private static DeviceInfoDataNative[] GetDevicesInfoData(SafeDeviceInfoSetHandle handle)
{
List<DeviceInfoDataNative> _data = new List<DeviceInfoDataNative>();
DeviceInfoDataNative deviceInfoData = new DeviceInfoDataNative();
int index = 0;
int deviceInfoDataSize = Marshal.SizeOf(deviceInfoData);
deviceInfoData.Size = deviceInfoDataSize;
while (SetupDiEnumDeviceInfo(handle, index, ref deviceInfoData))
{
_data.Add(deviceInfoData);
index += 1;
deviceInfoData = new DeviceInfoDataNative();
deviceInfoData.Size = deviceInfoDataSize;
}
return _data.ToArray();
}
private static int GetIndexOfInstance(SafeDeviceInfoSetHandle handle, DeviceInfoDataNative[] diData, string instanceId)
{
const int ERROR_INSUFFICIENT_BUFFER = 122;
for (int index = 0; index <= diData.Length - 1; index++)
{
StringBuilder sb = new StringBuilder(1);
int requiredSize = 0;
bool result = SetupDiGetDeviceInstanceId(handle.DangerousGetHandle(), ref diData[index], sb, sb.Capacity, out requiredSize);
if (result == false && Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
{
sb.Capacity = requiredSize;
result = SetupDiGetDeviceInstanceId(handle.DangerousGetHandle(), ref diData[index], sb, sb.Capacity, out requiredSize);
}
if (result == false)
throw new Win32Exception();
if (instanceId.Equals(sb.ToString()))
{
return index;
}
}
// not found
return -1;
}
public static bool UninstallDevice(Guid classGuid, string instanceId)
{
SafeDeviceInfoSetHandle handle = null;
bool result = false;
try
{
// Get the handle to a device information set for all devices matching classGuid that are present on the system.
handle = SetupDiGetClassDevs(ref classGuid, instanceId, IntPtr.Zero, SetupDiGetClassDevsFlags.AllClasses | SetupDiGetClassDevsFlags.DeviceInterface);
if (handle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Get the device information data for each matching device.
DeviceInfoDataNative data = GetDeviceInfoData(handle);
// Find the index of our instance. i.e. the touchpad mouse - I have 3 mice attached...
//int index = GetIndexOfInstance(handle, diData, instanceId);
// TODO: Check the data structure first
// Uninstall
result = StartUninstallDevice(handle, data);
}
finally
{
if (handle != null)
{
if (handle.IsClosed == false)
{
handle.Close();
}
handle.Dispose();
}
}
return result;
}
private static bool StartUninstallDevice(SafeDeviceInfoSetHandle handle, DeviceInfoDataNative data)
{
ClassInstallHeader header = new ClassInstallHeader();
RemoveDeviceParameters removalParameters = new RemoveDeviceParameters();
bool needsReboot;
removalParameters.ClassInstallHeader.Size = Marshal.SizeOf(header);
removalParameters.ClassInstallHeader.InstallFunction = DiFunction.Remove;
removalParameters.Scope = Scope.Global;
removalParameters.HwProfile = 0;
bool result = SetupDiSetClassInstallParams(handle, ref data, ref removalParameters, Marshal.SizeOf(removalParameters));
if (result == false)
throw new Win32Exception();
result = DiUninstallDevice(IntPtr.Zero, handle, ref data, 0, out needsReboot);
// TODO: Check if need reboot
if (result == false)
{
int error = Marshal.GetLastWin32Error();
if (error == (int)SetupApiError.NotDisableable)
throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager)");
else if (error >= (int)SetupApiError.NoAssociatedClass && error <= (int)SetupApiError.OnlyValidateViaAuthenticode)
throw new Win32Exception("SetupAPI Error: " + ((SetupApiError)error).ToString());
else
throw new Win32Exception();
}
return result;
}
public static void RemoveDevice(Guid classGuid, string instanceId)
{
SafeDeviceInfoSetHandle handle = null;
try
{
// Get the handle to a device information set for all devices matching classGuid that are present on the system.
handle = SetupDiGetClassDevs(ref classGuid, instanceId, IntPtr.Zero, SetupDiGetClassDevsFlags.AllClasses | SetupDiGetClassDevsFlags.DeviceInterface);
if (handle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Get the device information data for each matching device.
DeviceInfoDataNative data = GetDeviceInfoData(handle);
// Find the index of our instance. i.e. the touchpad mouse - I have 3 mice attached...
//int index = GetIndexOfInstance(handle, diData, instanceId);
// Uninstall
bool result = StartRemoveDevice(handle, data);
}
finally
{
if (handle != null)
{
if (handle.IsClosed == false)
{
handle.Close();
}
handle.Dispose();
}
}
}
private static bool StartRemoveDevice(SafeDeviceInfoSetHandle handle, DeviceInfoDataNative data)
{
ClassInstallHeader header = new ClassInstallHeader();
RemoveDeviceParameters removalParameters = new RemoveDeviceParameters();
removalParameters.ClassInstallHeader.Size = Marshal.SizeOf(header);
removalParameters.ClassInstallHeader.InstallFunction = DiFunction.Remove;
removalParameters.Scope = Scope.Global;
removalParameters.HwProfile = 0;
bool result = SetupDiSetClassInstallParams(handle, ref data, ref removalParameters, Marshal.SizeOf(removalParameters));
if (result == false)
throw new Win32Exception();
result = SetupDiCallClassInstaller(DiFunction.Remove, handle, ref data);
if (result == false)
{
int error = Marshal.GetLastWin32Error();
if (error == (int)SetupApiError.NotDisableable)
throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager).");
else if (error >= (int)SetupApiError.NoAssociatedClass && error <= (int)SetupApiError.OnlyValidateViaAuthenticode)
throw new Win32Exception("SetupAPI Error: " + ((SetupApiError)error).ToString());
else
throw new Win32Exception();
}
return result;
}
}
}
Usage:
/////* CD-ROM as an example */////
// Found in the Device Manager under <Device> -> Properties -> Details -> Class Guid
Guid cdromClassGuid = new Guid("4d36e965-e325-11ce-bfc1-08002be10318");
// Found using WMI calls -> Disk -> Partitions -> LogicalDisks
// For the CD-ROM example: Device Manager under <Device> -> Properties -> Details -> Device Instance Path
string cdromInstancePath = #"SCSI\CDROM&VEN_MATSHITA&PROD_BD-RE_UJ260AF\4&315C1285&0&000000";
bool success = SetupApiWrapper.UninstallDevice(cdromClassGuid, cdromInstancePath);

Anyone using a BME280 sensor on Windows Core IoT?

I am trying to read data from a Bosch BME280 on Windows IoT Core. I am able to reset the chip, read the chip ID, get the trimming values and read the temp/press/hum values (burst mode). However, the compensated values are not correct. Here are the values I am getting now. I am hoping someone can share some values that I can use for comparison. Will post code in follow on post. Thanks.
DT1 0x196e, DT2 0x7e66, DT3 0x3200
DP1 0xc78f, DP2 0xded5, DP3 0xd00b, DP4 0xae1b, DP5 0xf00, DP6 0xf9ff, DP7 0xac26, DP8 0xad8, DP9 0xbd10
DH1 0x4b, DH2 0x6d01, DH3 0x0, DH4 0x1308, DH5 0x800, DH6 0x1e
Raw Temp: 0x7fd10, Raw Press: 0x581bc, Raw Humid: 0x6cca
Compensated values here:
BME280: Temp: 187.36c Pressure: 1344.55 millibars Humidity: 100 %rH
I am sure I am just doing something dumb, just need a little nudge in the right direction. Thanks.
Definitions of commands and way I read the trimming values. (just temp in example)
public static class BME280Commands
{
public static byte[] ChipID = {0xD0 };
public static byte[] Version = { 0xD1 };
public static byte[] SoftReset = { 0xE0, 0xB6 };
public static byte[] ControlHumidity = { 0xF2, 0x04 }; // second parm was 0x01
public static byte[] Status = { 0xF3 };
public static byte[] Control = { 0xF4, 0x91 }; // second parm was 0x87
public static byte[] Control1 = { 0xf4, 0x3f };
public static byte[] Config = { 0xF5, 0x16 };
public static byte[] PressureData = { 0xF7 };
public static byte[] TemperatureData = { 0xFA };
public static byte[] HumidityData = { 0xFD };
public static byte[] DIG_T1 = { 0x88 };
public static byte[] DIG_T2 = { 0x8A };
public static byte[] DIG_T3 = { 0x8C };
public static byte[] DIG_P1 = { 0x8E };
public static byte[] DIG_P2 = { 0x90 };
public static byte[] DIG_P3 = { 0x92 };
public static byte[] DIG_P4 = { 0x94 };
public static byte[] DIG_P5 = { 0x96 };
public static byte[] DIG_P6 = { 0x98 };
public static byte[] DIG_P7 = { 0x9A };
public static byte[] DIG_P8 = { 0x9C };
public static byte[] DIG_P9 = { 0x9E };
public static byte[] DIG_H1 = { 0xA1 };
public static byte[] DIG_H2 = { 0xE1 };
public static byte[] DIG_H3 = { 0xE3 };
public static byte[] DIG_H4 = { 0xE4 };
public static byte[] DIG_H5 = { 0xE5 };
public static byte[] DIG_H6 = { 0xE7 };
public static byte ExpectedChipId = 0x60;
public static byte SlaveAddress = 0x77;
public static byte SoftResetCode = 0xb6;
public Configure()
{
var data = new byte[1];
bme280Sensor.WriteRead(BME280Commands.SoftReset, data);
bme280Sensor.WriteRead(BME280Commands.ChipID, Id);
if (Id[0] == BME280Commands.ExpectedChipId)
{ // How I read the trimming values
bme280Sensor.WriteRead(BME280Commands.DIG_T1, buf2);
_digT1 = (UInt32)((buf2[0] << 8) | buf2[1]);
bme280Sensor.WriteRead(BME280Commands.DIG_T2, buf2);
_digT2 = ((buf2[0] << 8) | buf2[1]);
bme280Sensor.WriteRead(BME280Commands.DIG_T3, buf2);
_digT3 = ((buf2[0] << 8) | buf2[1]);
}
}
How I read the actual values
var buf8 = new byte[8];
bme280Sensor.Write(BME280Commands.ControlHumidity);
bme280Sensor.Write(BME280Commands.Control);
bme280Sensor.WriteRead(BME280Commands.PressureData, buf8);
_rawPress = (buf8[0] << 16 | buf8[1] << 8 | buf8[2]) >> 4;
_rawTemp = (buf8[3] << 16 | buf8[4] << 8 | buf8[5]) >> 4;
_rawHumid = (buf8[6] << 8) | buf8[7];
I think you are doing everything right.
However, following the raw values you provide, and I use the below math to calculate compensated temperature, for example,
int _rawTemp = 0x7fd10;
int _digT1 = 0x196e;
int _digT2 = 0x7e66;
int _digT3 = 0x3200;
int var1 = (((_rawTemp >> 3 - _digT1 << 1)) * _digT2) >> 11;
int var2 = (((((_rawTemp >> 4) - (_digT1)) * ((_rawTemp >> 4) - (_digT1))) >> 12) * (_digT3)) >> 14;
int t_fine = var1 + var2;
int temperature = ((t_fine) * 5 + 128) >> 8;
And I get 2559, which reads 25.59degreeC.
See to
https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
How did you calculate compensated values?

How to use resolve the zkemkeeper embedd issue?

Please check the code below :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using iTimeService.dsitimeTableAdapters;
using System.IO;
namespace iTimeService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
TENTERTableAdapter tenteradapter = new TENTERTableAdapter();
T012_GATETableAdapter gateadapter = new T012_GATETableAdapter();
}
}
I am getting an error on the object creation of zkemkeeper.CZKEMClass where it says : interop type 'zkemkeeper.CZKEMClass' cannot be embedded. Use the application interface instead.
click on the reference you have, I think for that specific project that would be 'zkemkeeper'
then on its properties just set the 'Embed Interop Type' to 'False'
I hope this would help.
OK, Thanks!
private MayChamCongBLL _mayChamCongBLL = new MayChamCongBLL();
private MayChamCongDTO _mayChamCongDTO = new MayChamCongDTO();
// private System.Configuration.Configuration _ngonNgu = ConfigurationManager.OpenExeConfiguration("MitaAttendance.exe");
private int a;
private ArrayList arrMayChamCong = new ArrayList();
//public CZKEM axCZKEM1 = new CZKEM();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private int b;
// private Bar bar1;
private bool bIsConnected = false;
private int c;
private string sMaMayChamCong;
private string sSuDungWeb;
private int iMachineNumber = 1;
private int iNgonNgu;
private CZKEMClass axCZKEM1 = new CZKEMClass();
private static bool _bIsConnected = false;
private static int _iMachineNumber = 1;
private static int _errorCode = 0;
public bool GetConnectState()
{
return _bIsConnected;
}
private void SetConnectState(bool state)
{
_bIsConnected = state;
}
private int GetMachineNumber()
{
return _iMachineNumber;
}
public int sta_ConnectTCP(string ip, string port, string commKey)
{
if (ip == "" || port == "" || commKey == "")
{
return -1;// ip or port is null
}
if (Convert.ToInt32(port) <= 0 || Convert.ToInt32(port) > 65535)
{
return -1;
}
if (Convert.ToInt32(commKey) < 0 || Convert.ToInt32(commKey) > 999999)
{
return -1;
}
int idwErrorCode = 0;
axCZKEM1.SetCommPassword(Convert.ToInt32(commKey));
if (_bIsConnected)
{
axCZKEM1.Disconnect();
SetConnectState(false);
return -2; //disconnect
}
if (axCZKEM1.Connect_Net(ip, Convert.ToInt32(port)))
{
SetConnectState(true);
return 1;
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
return idwErrorCode;
}
}
public void sta_DisConnect()
{
if (GetConnectState())
{
axCZKEM1.Disconnect();
}
}
public int sta_ReadNewAttLog(DataTable dt_log)
{
if (GetConnectState() == false)
{
//Please connect first!";
return -1024;
}
int ret = 0;
axCZKEM1.EnableDevice(GetMachineNumber(), false);//disable the device
string sdwEnrollNumber = "";
int idwVerifyMode = 0;
int idwInOutMode = 0;
int idwYear = 0;
int idwMonth = 0;
int idwDay = 0;
int idwHour = 0;
int idwMinute = 0;
int idwSecond = 0;
int idwWorkcode = 0;
if (axCZKEM1.ReadNewGLogData(GetMachineNumber()))
{
while (axCZKEM1.SSR_GetGeneralLogData(GetMachineNumber(), out sdwEnrollNumber, out idwVerifyMode,
out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory
{
DataRow dr = dt_log.NewRow();
dr["User ID"] = sdwEnrollNumber;
dr["Verify Date"] = idwYear + "-" + idwMonth + "-" + idwDay + " " + idwHour + ":" + idwMinute + ":" + idwSecond;
dr["idwYear"] = idwYear;
dr["idwMonth"] = idwMonth;
dr["idwDay"] = idwDay;
dr["idwHour"] = idwHour;
dr["idwMinute"] = idwMinute;
dr["idwSecond"] = idwSecond;
dr["Verify Type"] = idwVerifyMode;
dr["Verify State"] = idwInOutMode;
dr["WorkCode"] = idwWorkcode;
dt_log.Rows.Add(dr);
}
ret = 1;
}
else
{
axCZKEM1.GetLastError(ref _errorCode);
ret = _errorCode;
if (_errorCode != 0)
{
//"*Read attlog by period failed,ErrorCode: " + idwErrorCode.ToString();
}
else
{
//"No data from terminal returns!";
}
}
//lblOutputInfo.Items.Add("[func ReadNewGLogData]Temporarily unsupported");
axCZKEM1.EnableDevice(GetMachineNumber(), true);//enable the device
return ret;
}

Determine which process (b)locks a file, programmatically (under Windows >= XP) [duplicate]

I've seen several of answers about using Handle or Process Monitor, but I would like to be able to find out in my own code (C#)
which process is locking a file.
I have a nasty feeling that I'm going to have to spelunk around in the win32 API, but if anyone has already done this and can put me on the right track, I'd really appreciate the help.
Update
Links to similar questions
How does one figure out what process locked a file using c#?
Command line tool
Across a Network
Locking a USB device
Unit test fails with locked file
deleting locked file
Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked.
I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Collections.Generic;
static public class FileUtil
{
[StructLayout(LayoutKind.Sequential)]
struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
UInt32 nFiles,
string[] rgsFilenames,
UInt32 nApplications,
[In] RM_UNIQUE_PROCESS[] rgApplications,
UInt32 nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
///
/// </remarks>
static public List<Process> WhoIsLocking(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int ERROR_MORE_DATA = 234;
uint pnProcInfoNeeded = 0,
pnProcInfo = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == ERROR_MORE_DATA)
{
// Create an array to store the process results
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
pnProcInfo = pnProcInfoNeeded;
// Get the list
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res == 0)
{
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
// list to be returned
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
// catch the error -- in case the process is no longer running
catch (ArgumentException) { }
}
}
else throw new Exception("Could not list processes locking resource.");
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return processes;
}
}
Using from Limited Permission (e.g. IIS)
This call accesses the registry. If the process does not have permission to do so, you will get ERROR_WRITE_FAULT, meaning An operation was unable to read or write to the registry. You could selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.
Granting other-than-minimal permissions to the IIS user is a security risk.
This question had an original answer that is now over 7 years old. That code is preserved at https://gist.github.com/i-e-b/2290426
This old version might work for you if you need to use Windows XP for some reason.
A much better answer is at How to check for file lock?
I've replicated Eric J's answer below (with using statements added, and class & method names to match the old code that was here) Please note that the comments to this answer may be out-of-date.
Research by user 'Walkman' is ongoing to improve the older code, as there are some conditions where the Restart Manager does not list all locks. See Github repo: https://github.com/Walkman100/FileLocks
Use like:
List<Process> locks = Win32Processes.GetProcessesLockingFile(#"C:\Hello.docx");
Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace FileLockInfo
{
public static class Win32Processes
{
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
/// </remarks>
public static List<Process> GetProcessesLockingFile(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int MORE_DATA = 234;
uint pnProcInfoNeeded, pnProcInfo = 0, lpdwRebootReasons = RmRebootReasonNone;
string[] resources = {path}; // Just checking on one resource.
res = RmRegisterResources(handle, (uint) resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == MORE_DATA)
{
return EnumerateProcesses(pnProcInfoNeeded, handle, lpdwRebootReasons);
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return new List<Process>();
}
[StructLayout(LayoutKind.Sequential)]
public struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
public enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)] public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)] public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)] public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle, uint nFiles, string[] rgsFilenames,
uint nApplications, [In] RM_UNIQUE_PROCESS[] rgApplications, uint nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle, out uint pnProcInfoNeeded,
ref uint pnProcInfo, [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
private static List<Process> EnumerateProcesses(uint pnProcInfoNeeded, uint handle, uint lpdwRebootReasons)
{
var processes = new List<Process>(10);
// Create an array to store the process results
var processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
var pnProcInfo = pnProcInfoNeeded;
// Get the list
var res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res != 0) throw new Exception("Could not list processes locking resource.");
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
catch (ArgumentException) { } // catch the error -- in case the process is no longer running
}
return processes;
}
}
}
It is very complex to invoke Win32 from C#.
You should use the tool Handle.exe.
After that your C# code have to be the following:
string fileName = #"c:\aaa.doc";//Path to locked file
Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
One of the good things about handle.exe is that you can run it as a subprocess and parse the output.
We do this in our deployment script - works like a charm.
The code I found here,
https://vmccontroller.svn.codeplex.com/svn/VmcController/VmcServices/DetectOpenFiles.cs
Works for me much better than the code provided by Iain. Iain's code seemed to be acquiring a lock of its own. Here is my slightly modified version of the code above modified to return the string path of the files locked instead of the FileSystemInfo object,
using System;
using System.Collections.Generic;
//using System.EnterpriseServices;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace Crmc.Core.BuildTasks
{
using System.Diagnostics;
using System.Linq;
#region ENUMs
internal enum NT_STATUS
{
STATUS_SUCCESS = 0x00000000,
STATUS_BUFFER_OVERFLOW = unchecked((int)0x80000005L),
STATUS_INFO_LENGTH_MISMATCH = unchecked((int)0xC0000004L)
}
internal enum SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation = 0,
SystemPerformanceInformation = 2,
SystemTimeOfDayInformation = 3,
SystemProcessInformation = 5,
SystemProcessorPerformanceInformation = 8,
SystemHandleInformation = 16,
SystemInterruptInformation = 23,
SystemExceptionInformation = 33,
SystemRegistryQuotaInformation = 37,
SystemLookasideInformation = 45
}
internal enum OBJECT_INFORMATION_CLASS
{
ObjectBasicInformation = 0,
ObjectNameInformation = 1,
ObjectTypeInformation = 2,
ObjectAllTypesInformation = 3,
ObjectHandleInformation = 4
}
[Flags]
internal enum ProcessAccessRights
{
PROCESS_DUP_HANDLE = 0x00000040
}
[Flags]
internal enum DuplicateHandleOptions
{
DUPLICATE_CLOSE_SOURCE = 0x1,
DUPLICATE_SAME_ACCESS = 0x2
}
#endregion
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
internal sealed class SafeObjectHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeObjectHandle()
: base(true)
{ }
internal SafeObjectHandle(IntPtr preexistingHandle, bool ownsHandle)
: base(ownsHandle)
{
base.SetHandle(preexistingHandle);
}
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(base.handle);
}
}
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeProcessHandle()
: base(true)
{ }
internal SafeProcessHandle(IntPtr preexistingHandle, bool ownsHandle)
: base(ownsHandle)
{
base.SetHandle(preexistingHandle);
}
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(base.handle);
}
}
#region Native Methods
internal static class NativeMethods
{
[DllImport("ntdll.dll")]
internal static extern NT_STATUS NtQuerySystemInformation(
[In] SYSTEM_INFORMATION_CLASS SystemInformationClass,
[In] IntPtr SystemInformation,
[In] int SystemInformationLength,
[Out] out int ReturnLength);
[DllImport("ntdll.dll")]
internal static extern NT_STATUS NtQueryObject(
[In] IntPtr Handle,
[In] OBJECT_INFORMATION_CLASS ObjectInformationClass,
[In] IntPtr ObjectInformation,
[In] int ObjectInformationLength,
[Out] out int ReturnLength);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern SafeProcessHandle OpenProcess(
[In] ProcessAccessRights dwDesiredAccess,
[In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
[In] int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DuplicateHandle(
[In] IntPtr hSourceProcessHandle,
[In] IntPtr hSourceHandle,
[In] IntPtr hTargetProcessHandle,
[Out] out SafeObjectHandle lpTargetHandle,
[In] int dwDesiredAccess,
[In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
[In] DuplicateHandleOptions dwOptions);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int GetProcessId(
[In] IntPtr Process);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(
[In] IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int QueryDosDevice(
[In] string lpDeviceName,
[Out] StringBuilder lpTargetPath,
[In] int ucchMax);
}
#endregion
//[ComVisible(true), EventTrackingEnabled(true)]
public class DetectOpenFiles// : ServicedComponent
{
private static Dictionary<string, string> deviceMap;
private const string networkDevicePrefix = "\\Device\\LanmanRedirector\\";
private const int MAX_PATH = 260;
private enum SystemHandleType
{
OB_TYPE_UNKNOWN = 0,
OB_TYPE_TYPE = 1,
OB_TYPE_DIRECTORY,
OB_TYPE_SYMBOLIC_LINK,
OB_TYPE_TOKEN,
OB_TYPE_PROCESS,
OB_TYPE_THREAD,
OB_TYPE_UNKNOWN_7,
OB_TYPE_EVENT,
OB_TYPE_EVENT_PAIR,
OB_TYPE_MUTANT,
OB_TYPE_UNKNOWN_11,
OB_TYPE_SEMAPHORE,
OB_TYPE_TIMER,
OB_TYPE_PROFILE,
OB_TYPE_WINDOW_STATION,
OB_TYPE_DESKTOP,
OB_TYPE_SECTION,
OB_TYPE_KEY,
OB_TYPE_PORT,
OB_TYPE_WAITABLE_PORT,
OB_TYPE_UNKNOWN_21,
OB_TYPE_UNKNOWN_22,
OB_TYPE_UNKNOWN_23,
OB_TYPE_UNKNOWN_24,
//OB_TYPE_CONTROLLER,
//OB_TYPE_DEVICE,
//OB_TYPE_DRIVER,
OB_TYPE_IO_COMPLETION,
OB_TYPE_FILE
};
private const int handleTypeTokenCount = 27;
private static readonly string[] handleTypeTokens = new string[] {
"", "", "Directory", "SymbolicLink", "Token",
"Process", "Thread", "Unknown7", "Event", "EventPair", "Mutant",
"Unknown11", "Semaphore", "Timer", "Profile", "WindowStation",
"Desktop", "Section", "Key", "Port", "WaitablePort",
"Unknown21", "Unknown22", "Unknown23", "Unknown24",
"IoCompletion", "File"
};
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_HANDLE_ENTRY
{
public int OwnerPid;
public byte ObjectType;
public byte HandleFlags;
public short HandleValue;
public int ObjectPointer;
public int AccessMask;
}
/// <summary>
/// Gets the open files enumerator.
/// </summary>
/// <param name="processId">The process id.</param>
/// <returns></returns>
public static IEnumerable<String> GetOpenFilesEnumerator(int processId)
{
return new OpenFiles(processId);
}
public static List<Process> GetProcessesUsingFile(string fName)
{
List<Process> result = new List<Process>();
foreach (var p in Process.GetProcesses())
{
try
{
if (DetectOpenFiles.GetOpenFilesEnumerator(p.Id).Contains(fName))
{
result.Add(p);
}
}
catch { }//some processes will fail
}
return result;
}
private sealed class OpenFiles : IEnumerable<String>
{
private readonly int processId;
internal OpenFiles(int processId)
{
this.processId = processId;
}
#region IEnumerable<FileSystemInfo> Members
public IEnumerator<String> GetEnumerator()
{
NT_STATUS ret;
int length = 0x10000;
// Loop, probing for required memory.
do
{
IntPtr ptr = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
// CER guarantees that the address of the allocated
// memory is actually assigned to ptr if an
// asynchronous exception occurs.
ptr = Marshal.AllocHGlobal(length);
}
int returnLength;
ret = NativeMethods.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, length, out returnLength);
if (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH)
{
// Round required memory up to the nearest 64KB boundary.
length = ((returnLength + 0xffff) & ~0xffff);
}
else if (ret == NT_STATUS.STATUS_SUCCESS)
{
int handleCount = Marshal.ReadInt32(ptr);
int offset = sizeof(int);
int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_ENTRY));
for (int i = 0; i < handleCount; i++)
{
SYSTEM_HANDLE_ENTRY handleEntry = (SYSTEM_HANDLE_ENTRY)Marshal.PtrToStructure((IntPtr)((int)ptr + offset), typeof(SYSTEM_HANDLE_ENTRY));
if (handleEntry.OwnerPid == processId)
{
IntPtr handle = (IntPtr)handleEntry.HandleValue;
SystemHandleType handleType;
if (GetHandleType(handle, handleEntry.OwnerPid, out handleType) && handleType == SystemHandleType.OB_TYPE_FILE)
{
string devicePath;
if (GetFileNameFromHandle(handle, handleEntry.OwnerPid, out devicePath))
{
string dosPath;
if (ConvertDevicePathToDosPath(devicePath, out dosPath))
{
if (File.Exists(dosPath))
{
yield return dosPath; // return new FileInfo(dosPath);
}
else if (Directory.Exists(dosPath))
{
yield return dosPath; // new DirectoryInfo(dosPath);
}
}
}
}
}
offset += size;
}
}
}
finally
{
// CER guarantees that the allocated memory is freed,
// if an asynchronous exception occurs.
Marshal.FreeHGlobal(ptr);
//sw.Flush();
//sw.Close();
}
}
while (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
#region Private Members
private static bool GetFileNameFromHandle(IntPtr handle, int processId, out string fileName)
{
IntPtr currentProcess = NativeMethods.GetCurrentProcess();
bool remote = (processId != NativeMethods.GetProcessId(currentProcess));
SafeProcessHandle processHandle = null;
SafeObjectHandle objectHandle = null;
try
{
if (remote)
{
processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId);
if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
{
handle = objectHandle.DangerousGetHandle();
}
}
return GetFileNameFromHandle(handle, out fileName, 200);
}
finally
{
if (remote)
{
if (processHandle != null)
{
processHandle.Close();
}
if (objectHandle != null)
{
objectHandle.Close();
}
}
}
}
private static bool GetFileNameFromHandle(IntPtr handle, out string fileName, int wait)
{
using (FileNameFromHandleState f = new FileNameFromHandleState(handle))
{
ThreadPool.QueueUserWorkItem(new WaitCallback(GetFileNameFromHandle), f);
if (f.WaitOne(wait))
{
fileName = f.FileName;
return f.RetValue;
}
else
{
fileName = string.Empty;
return false;
}
}
}
private class FileNameFromHandleState : IDisposable
{
private ManualResetEvent _mr;
private IntPtr _handle;
private string _fileName;
private bool _retValue;
public IntPtr Handle
{
get
{
return _handle;
}
}
public string FileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
public bool RetValue
{
get
{
return _retValue;
}
set
{
_retValue = value;
}
}
public FileNameFromHandleState(IntPtr handle)
{
_mr = new ManualResetEvent(false);
this._handle = handle;
}
public bool WaitOne(int wait)
{
return _mr.WaitOne(wait, false);
}
public void Set()
{
try
{
_mr.Set();
}
catch{}
}
#region IDisposable Members
public void Dispose()
{
if (_mr != null)
_mr.Close();
}
#endregion
}
private static void GetFileNameFromHandle(object state)
{
FileNameFromHandleState s = (FileNameFromHandleState)state;
string fileName;
s.RetValue = GetFileNameFromHandle(s.Handle, out fileName);
s.FileName = fileName;
s.Set();
}
private static bool GetFileNameFromHandle(IntPtr handle, out string fileName)
{
IntPtr ptr = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
int length = 0x200; // 512 bytes
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
// CER guarantees the assignment of the allocated
// memory address to ptr, if an ansynchronous exception
// occurs.
ptr = Marshal.AllocHGlobal(length);
}
NT_STATUS ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
if (ret == NT_STATUS.STATUS_BUFFER_OVERFLOW)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
// CER guarantees that the previous allocation is freed,
// and that the newly allocated memory address is
// assigned to ptr if an asynchronous exception occurs.
Marshal.FreeHGlobal(ptr);
ptr = Marshal.AllocHGlobal(length);
}
ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
}
if (ret == NT_STATUS.STATUS_SUCCESS)
{
fileName = Marshal.PtrToStringUni((IntPtr)((int)ptr + 8), (length - 9) / 2);
return fileName.Length != 0;
}
}
finally
{
// CER guarantees that the allocated memory is freed,
// if an asynchronous exception occurs.
Marshal.FreeHGlobal(ptr);
}
fileName = string.Empty;
return false;
}
private static bool GetHandleType(IntPtr handle, int processId, out SystemHandleType handleType)
{
string token = GetHandleTypeToken(handle, processId);
return GetHandleTypeFromToken(token, out handleType);
}
private static bool GetHandleType(IntPtr handle, out SystemHandleType handleType)
{
string token = GetHandleTypeToken(handle);
return GetHandleTypeFromToken(token, out handleType);
}
private static bool GetHandleTypeFromToken(string token, out SystemHandleType handleType)
{
for (int i = 1; i < handleTypeTokenCount; i++)
{
if (handleTypeTokens[i] == token)
{
handleType = (SystemHandleType)i;
return true;
}
}
handleType = SystemHandleType.OB_TYPE_UNKNOWN;
return false;
}
private static string GetHandleTypeToken(IntPtr handle, int processId)
{
IntPtr currentProcess = NativeMethods.GetCurrentProcess();
bool remote = (processId != NativeMethods.GetProcessId(currentProcess));
SafeProcessHandle processHandle = null;
SafeObjectHandle objectHandle = null;
try
{
if (remote)
{
processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId);
if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
{
handle = objectHandle.DangerousGetHandle();
}
}
return GetHandleTypeToken(handle);
}
finally
{
if (remote)
{
if (processHandle != null)
{
processHandle.Close();
}
if (objectHandle != null)
{
objectHandle.Close();
}
}
}
}
private static string GetHandleTypeToken(IntPtr handle)
{
int length;
NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, IntPtr.Zero, 0, out length);
IntPtr ptr = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
ptr = Marshal.AllocHGlobal(length);
}
if (NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, ptr, length, out length) == NT_STATUS.STATUS_SUCCESS)
{
return Marshal.PtrToStringUni((IntPtr)((int)ptr + 0x60));
}
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return string.Empty;
}
private static bool ConvertDevicePathToDosPath(string devicePath, out string dosPath)
{
EnsureDeviceMap();
int i = devicePath.Length;
while (i > 0 && (i = devicePath.LastIndexOf('\\', i - 1)) != -1)
{
string drive;
if (deviceMap.TryGetValue(devicePath.Substring(0, i), out drive))
{
dosPath = string.Concat(drive, devicePath.Substring(i));
return dosPath.Length != 0;
}
}
dosPath = string.Empty;
return false;
}
private static void EnsureDeviceMap()
{
if (deviceMap == null)
{
Dictionary<string, string> localDeviceMap = BuildDeviceMap();
Interlocked.CompareExchange<Dictionary<string, string>>(ref deviceMap, localDeviceMap, null);
}
}
private static Dictionary<string, string> BuildDeviceMap()
{
string[] logicalDrives = Environment.GetLogicalDrives();
Dictionary<string, string> localDeviceMap = new Dictionary<string, string>(logicalDrives.Length);
StringBuilder lpTargetPath = new StringBuilder(MAX_PATH);
foreach (string drive in logicalDrives)
{
string lpDeviceName = drive.Substring(0, 2);
NativeMethods.QueryDosDevice(lpDeviceName, lpTargetPath, MAX_PATH);
localDeviceMap.Add(NormalizeDeviceName(lpTargetPath.ToString()), lpDeviceName);
}
localDeviceMap.Add(networkDevicePrefix.Substring(0, networkDevicePrefix.Length - 1), "\\");
return localDeviceMap;
}
private static string NormalizeDeviceName(string deviceName)
{
if (string.Compare(deviceName, 0, networkDevicePrefix, 0, networkDevicePrefix.Length, StringComparison.InvariantCulture) == 0)
{
string shareName = deviceName.Substring(deviceName.IndexOf('\\', networkDevicePrefix.Length) + 1);
return string.Concat(networkDevicePrefix, shareName);
}
return deviceName;
}
#endregion
}
}
Not very straightforward, but on Windows Vista and above you can use the Restart Manager APIs to see who is using a file. Internet Explorer caches settings includes details on using this to detect which process has iexplore.exe open.
Omitting a lot of detail:
// Start an RM session
RmStartSession(&sessionHandle, 0, sessionKey);
// Register the file you are checking
RmRegisterResources(sessionHandle, 1, filePathArray, 0, NULL, 0, NULL);
// Get all processes that have that file open.
RmGetList(sessionHAndle, &nProcInfoNeeded, &nProcInfo, processes, &rebootReason);
RmEndSession(sessionHandle);
Handle, from Windows Sysinternals. This is a free command-line utility provided by Microsoft.
You could run it, and parse the result.
I had issues with stefan's solution. Below is a modified version which seems to work well.
using System;
using System.Collections;
using System.Diagnostics;
using System.Management;
using System.IO;
static class Module1
{
static internal ArrayList myProcessArray = new ArrayList();
private static Process myProcess;
public static void Main()
{
string strFile = "c:\\windows\\system32\\msi.dll";
ArrayList a = getFileProcesses(strFile);
foreach (Process p in a)
{
Debug.Print(p.ProcessName);
}
}
private static ArrayList getFileProcesses(string strFile)
{
myProcessArray.Clear();
Process[] processes = Process.GetProcesses();
int i = 0;
for (i = 0; i <= processes.GetUpperBound(0) - 1; i++)
{
myProcess = processes[i];
//if (!myProcess.HasExited) //This will cause an "Access is denied" error
if (myProcess.Threads.Count > 0)
{
try
{
ProcessModuleCollection modules = myProcess.Modules;
int j = 0;
for (j = 0; j <= modules.Count - 1; j++)
{
if ((modules[j].FileName.ToLower().CompareTo(strFile.ToLower()) == 0))
{
myProcessArray.Add(myProcess);
break;
// TODO: might not be correct. Was : Exit For
}
}
}
catch (Exception exception)
{
//MsgBox(("Error : " & exception.Message))
}
}
}
return myProcessArray;
}
}
UPDATE
If you just want to know which process(es) are locking a particular DLL, you can execute and parse the output of tasklist /m YourDllName.dll. Works on Windows XP and later. See
What does this do? tasklist /m "mscor*"
This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.
C#:
using System.Management;
using System.IO;
static class Module1
{
static internal ArrayList myProcessArray = new ArrayList();
private static Process myProcess;
public static void Main()
{
string strFile = "c:\\windows\\system32\\msi.dll";
ArrayList a = getFileProcesses(strFile);
foreach (Process p in a) {
Debug.Print(p.ProcessName);
}
}
private static ArrayList getFileProcesses(string strFile)
{
myProcessArray.Clear();
Process[] processes = Process.GetProcesses;
int i = 0;
for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) {
myProcess = processes(i);
if (!myProcess.HasExited) {
try {
ProcessModuleCollection modules = myProcess.Modules;
int j = 0;
for (j = 0; j <= modules.Count - 1; j++) {
if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) {
myProcessArray.Add(myProcess);
break; // TODO: might not be correct. Was : Exit For
}
}
}
catch (Exception exception) {
}
//MsgBox(("Error : " & exception.Message))
}
}
return myProcessArray;
}
}
VB.Net:
Imports System.Management
Imports System.IO
Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process
Sub Main()
Dim strFile As String = "c:\windows\system32\msi.dll"
Dim a As ArrayList = getFileProcesses(strFile)
For Each p As Process In a
Debug.Print(p.ProcessName)
Next
End Sub
Private Function getFileProcesses(ByVal strFile As String) As ArrayList
myProcessArray.Clear()
Dim processes As Process() = Process.GetProcesses
Dim i As Integer
For i = 0 To processes.GetUpperBound(0) - 1
myProcess = processes(i)
If Not myProcess.HasExited Then
Try
Dim modules As ProcessModuleCollection = myProcess.Modules
Dim j As Integer
For j = 0 To modules.Count - 1
If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
myProcessArray.Add(myProcess)
Exit For
End If
Next j
Catch exception As Exception
'MsgBox(("Error : " & exception.Message))
End Try
End If
Next i
Return myProcessArray
End Function
End Module
The following was produced based on Iain Ballard's code dump. It is broken: it will occasionally lock up when you retrieve the handle name. This code doesn't contain any work-arounds for that issue, and .NET leaves few options: Thread.Abort can no longer abort a thread that's currently in a native method.
So, with that disclaimer, here is the code to retrieve handles which has been adapted to work (apart from the occasional lock-up) both in 32 and 64 bit modes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace BrokenHandleRetrieval
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enumerates open handles.");
Console.WriteLine("This *will* lock up on calling HandleInfo.Name from time to time. Thread.Abort() won't help.");
foreach (var hi in HandleUtil.GetHandles().Where(hi => hi.Type == HandleType.File))
Console.WriteLine("pid: " + hi.ProcessId + ", name: " + hi.Name);
}
}
public enum HandleType
{
Unknown,
Other,
File, Directory, SymbolicLink, Key,
Process, Thread, Job, Session, WindowStation,
Timer, Desktop, Semaphore, Token,
Mutant, Section, Event, KeyedEvent, IoCompletion, IoCompletionReserve,
TpWorkerFactory, AlpcPort, WmiGuid, UserApcReserve,
}
public class HandleInfo
{
public int ProcessId { get; private set; }
public ushort Handle { get; private set; }
public int GrantedAccess { get; private set; }
public byte RawType { get; private set; }
public HandleInfo(int processId, ushort handle, int grantedAccess, byte rawType)
{
ProcessId = processId;
Handle = handle;
GrantedAccess = grantedAccess;
RawType = rawType;
}
private static Dictionary<byte, string> _rawTypeMap = new Dictionary<byte, string>();
private string _name, _typeStr;
private HandleType _type;
public string Name { get { if (_name == null) initTypeAndName(); return _name; } }
public string TypeString { get { if (_typeStr == null) initType(); return _typeStr; } }
public HandleType Type { get { if (_typeStr == null) initType(); return _type; } }
private void initType()
{
if (_rawTypeMap.ContainsKey(RawType))
{
_typeStr = _rawTypeMap[RawType];
_type = HandleTypeFromString(_typeStr);
}
else
initTypeAndName();
}
bool _typeAndNameAttempted = false;
private void initTypeAndName()
{
if (_typeAndNameAttempted)
return;
_typeAndNameAttempted = true;
IntPtr sourceProcessHandle = IntPtr.Zero;
IntPtr handleDuplicate = IntPtr.Zero;
try
{
sourceProcessHandle = NativeMethods.OpenProcess(0x40 /* dup_handle */, true, ProcessId);
// To read info about a handle owned by another process we must duplicate it into ours
// For simplicity, current process handles will also get duplicated; remember that process handles cannot be compared for equality
if (!NativeMethods.DuplicateHandle(sourceProcessHandle, (IntPtr) Handle, NativeMethods.GetCurrentProcess(), out handleDuplicate, 0, false, 2 /* same_access */))
return;
// Query the object type
if (_rawTypeMap.ContainsKey(RawType))
_typeStr = _rawTypeMap[RawType];
else
{
int length;
NativeMethods.NtQueryObject(handleDuplicate, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, IntPtr.Zero, 0, out length);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(length);
if (NativeMethods.NtQueryObject(handleDuplicate, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, ptr, length, out length) != NT_STATUS.STATUS_SUCCESS)
return;
_typeStr = Marshal.PtrToStringUni((IntPtr) ((int) ptr + 0x58 + 2 * IntPtr.Size));
_rawTypeMap[RawType] = _typeStr;
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
_type = HandleTypeFromString(_typeStr);
// Query the object name
if (_typeStr != null && GrantedAccess != 0x0012019f && GrantedAccess != 0x00120189 && GrantedAccess != 0x120089) // don't query some objects that could get stuck
{
int length;
NativeMethods.NtQueryObject(handleDuplicate, OBJECT_INFORMATION_CLASS.ObjectNameInformation, IntPtr.Zero, 0, out length);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(length);
if (NativeMethods.NtQueryObject(handleDuplicate, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length) != NT_STATUS.STATUS_SUCCESS)
return;
_name = Marshal.PtrToStringUni((IntPtr) ((int) ptr + 2 * IntPtr.Size));
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
}
finally
{
NativeMethods.CloseHandle(sourceProcessHandle);
if (handleDuplicate != IntPtr.Zero)
NativeMethods.CloseHandle(handleDuplicate);
}
}
public static HandleType HandleTypeFromString(string typeStr)
{
switch (typeStr)
{
case null: return HandleType.Unknown;
case "File": return HandleType.File;
case "IoCompletion": return HandleType.IoCompletion;
case "TpWorkerFactory": return HandleType.TpWorkerFactory;
case "ALPC Port": return HandleType.AlpcPort;
case "Event": return HandleType.Event;
case "Section": return HandleType.Section;
case "Directory": return HandleType.Directory;
case "KeyedEvent": return HandleType.KeyedEvent;
case "Process": return HandleType.Process;
case "Key": return HandleType.Key;
case "SymbolicLink": return HandleType.SymbolicLink;
case "Thread": return HandleType.Thread;
case "Mutant": return HandleType.Mutant;
case "WindowStation": return HandleType.WindowStation;
case "Timer": return HandleType.Timer;
case "Semaphore": return HandleType.Semaphore;
case "Desktop": return HandleType.Desktop;
case "Token": return HandleType.Token;
case "Job": return HandleType.Job;
case "Session": return HandleType.Session;
case "IoCompletionReserve": return HandleType.IoCompletionReserve;
case "WmiGuid": return HandleType.WmiGuid;
case "UserApcReserve": return HandleType.UserApcReserve;
default: return HandleType.Other;
}
}
}
public static class HandleUtil
{
public static IEnumerable<HandleInfo> GetHandles()
{
// Attempt to retrieve the handle information
int length = 0x10000;
IntPtr ptr = IntPtr.Zero;
try
{
while (true)
{
ptr = Marshal.AllocHGlobal(length);
int wantedLength;
var result = NativeMethods.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, length, out wantedLength);
if (result == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH)
{
length = Math.Max(length, wantedLength);
Marshal.FreeHGlobal(ptr);
ptr = IntPtr.Zero;
}
else if (result == NT_STATUS.STATUS_SUCCESS)
break;
else
throw new Exception("Failed to retrieve system handle information.");
}
int handleCount = IntPtr.Size == 4 ? Marshal.ReadInt32(ptr) : (int) Marshal.ReadInt64(ptr);
int offset = IntPtr.Size;
int size = Marshal.SizeOf(typeof(SystemHandleEntry));
for (int i = 0; i < handleCount; i++)
{
var struc = (SystemHandleEntry) Marshal.PtrToStructure((IntPtr) ((int) ptr + offset), typeof(SystemHandleEntry));
yield return new HandleInfo(struc.OwnerProcessId, struc.Handle, struc.GrantedAccess, struc.ObjectTypeNumber);
offset += size;
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
[StructLayout(LayoutKind.Sequential)]
private struct SystemHandleEntry
{
public int OwnerProcessId;
public byte ObjectTypeNumber;
public byte Flags;
public ushort Handle;
public IntPtr Object;
public int GrantedAccess;
}
}
enum NT_STATUS
{
STATUS_SUCCESS = 0x00000000,
STATUS_BUFFER_OVERFLOW = unchecked((int) 0x80000005L),
STATUS_INFO_LENGTH_MISMATCH = unchecked((int) 0xC0000004L)
}
enum SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation = 0,
SystemPerformanceInformation = 2,
SystemTimeOfDayInformation = 3,
SystemProcessInformation = 5,
SystemProcessorPerformanceInformation = 8,
SystemHandleInformation = 16,
SystemInterruptInformation = 23,
SystemExceptionInformation = 33,
SystemRegistryQuotaInformation = 37,
SystemLookasideInformation = 45
}
enum OBJECT_INFORMATION_CLASS
{
ObjectBasicInformation = 0,
ObjectNameInformation = 1,
ObjectTypeInformation = 2,
ObjectAllTypesInformation = 3,
ObjectHandleInformation = 4
}
static class NativeMethods
{
[DllImport("ntdll.dll")]
internal static extern NT_STATUS NtQuerySystemInformation(
[In] SYSTEM_INFORMATION_CLASS SystemInformationClass,
[In] IntPtr SystemInformation,
[In] int SystemInformationLength,
[Out] out int ReturnLength);
[DllImport("ntdll.dll")]
internal static extern NT_STATUS NtQueryObject(
[In] IntPtr Handle,
[In] OBJECT_INFORMATION_CLASS ObjectInformationClass,
[In] IntPtr ObjectInformation,
[In] int ObjectInformationLength,
[Out] out int ReturnLength);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
[In] int dwDesiredAccess,
[In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
[In] int dwProcessId);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(
[In] IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DuplicateHandle(
[In] IntPtr hSourceProcessHandle,
[In] IntPtr hSourceHandle,
[In] IntPtr hTargetProcessHandle,
[Out] out IntPtr lpTargetHandle,
[In] int dwDesiredAccess,
[In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
[In] int dwOptions);
}
}
This is probably irrelevant and if it is please someone comment but there was a work-around I've used in explorer before to get around file locks.
If a file was locked by a process that had died Windows often wouldn't let you delete it but if you created a new file of the same name somewhere else, moved it to the folder it would succeed. You could then delete the new file and all was well.
To use this for your app you'd have to be able to read the file and hold it in memory before you did this then you write it back out after you'd got rid of the old one.
Maybe it will help, maybe not but it's worth trying.
Try Unlocker. If you try and delete the file that is locked by another process, it will list the process(es) that have the file locked. You can then unlock the file by shutting down those processes.
foreach (var process in Process.GetProcessesByName("excel")) //whatever you need to close
{
if (process.MainWindowTitle.Contains("test.xlsx"))
{
process.Kill();
break;
}
}
or
foreach (var process in Process.GetProcesses())
{
if (process.MainWindowTitle.Contains("test.dat"))
{
process.Kill();
break;
}
}
I believe that you need code running in kernel mode to completely answer the question (but I haven't looked at the restart manager API).
You can enumerate all processes and their modules - so if the file you're looking for is a module (DLL, EXE, OCX...), you're good to go. But if it's a text file for example, you have to look at the kernel handle table which you cannot see from user mode. Handle.exe has a kernel driver in order to do that.
I rewrote the GetProcessesLockingFile() method in the solution. The code was not working.
For example, you have a folder "C:\folder1\folder2" and a process in folder2 (process1). If the process was running, GetProcessesLockingFile() was returning "C:\folder1\folder2". So the condition if (files.Contains(filePath)) => if ("C:\folder1\folder2".contains("C:\folder1\folder2\process1")) was never true.
So this is my solution:
public static List<Process> GetProcessesLockingFile(FileInfo file)
{
var procs = new List<Process>();
var processListSnapshot = Process.GetProcesses();
foreach (var process in processListSnapshot)
{
if (process.Id <= 4) { continue; } // system processes
List<string> paths = GetFilesLockedBy(process);
foreach (string path in paths)
{
string pathDirectory = path;
if (!pathDirectory.EndsWith(Constants.DOUBLE_BACKSLASH))
{
pathDirectory = pathDirectory + Constants.DOUBLE_BACKSLASH;
}
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(pathDirectory));
if (file.FullName.Contains(lastFolderName))
{
procs.Add(process);
}
}
}
return procs;
}
Or with a string parameter:
public static List<Process> GetProcessesLockingFile(string filePath)
{
var procs = new List<Process>();
var processListSnapshot = Process.GetProcesses();
foreach (var process in processListSnapshot)
{
if (process.Id <= 4) { continue; } // system processes
List<string> paths = GetFilesLockedBy(process);
foreach (string path in paths)
{
string pathDirectory = path;
if (!pathDirectory.EndsWith(Constants.DOUBLE_BACKSLASH))
{
pathDirectory = pathDirectory + Constants.DOUBLE_BACKSLASH;
}
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(pathDirectory));
if (filePath.Contains(lastFolderName))
{
procs.Add(process);
}
}
}
return procs;
}
You absolutely don't need to run in Kernel mode (!!!)
It's a Win32 FAQ since Windows 95 (!) (in C, Google groups, Win32) : read the handle table, from User mode of course, and get the PID from the File handle ...
Using dotnet core (net6) I solved this problem by using the win32 restart manager (as others have also mentioned). However some of the linked articles have elaborate code importing DLLs and calling those.
After finding an app to kill processes that lock a file written by meziantou. I found out that he publishes .Net wrappers for win32 dlls (including the restart manager).
Leveraging his work, I was able to fix this problem with the following code:
using Meziantou.Framework.Win32;
public static IEnumerable<Process> GetProcessesLockingFile(string filePath)
{
using var session = RestartManager.CreateSession();
session.RegisterFile(filePath);
return session.GetProcessesLockingResources();
}
simpler with linq:
public void KillProcessesAssociatedToFile(string file)
{
GetProcessesAssociatedToFile(file).ForEach(x =>
{
x.Kill();
x.WaitForExit(10000);
});
}
public List<Process> GetProcessesAssociatedToFile(string file)
{
return Process.GetProcesses()
.Where(x => !x.HasExited
&& x.Modules.Cast<ProcessModule>().ToList()
.Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())
).ToList();
}

How to programmatically check the "Password must meet complexity requirements" group policy setting?

Window has five group policy settings related to password security:
Enforce password history
Maximum password age
Minimum password age
Minimum password length
Password must meet complexity requirements
Store passwords using reversible encryption
I know how to use NetUserModalsGet to read most of these items. But it doesn't support checking if password complexity requirement is enabled:
Enforce password history: usrmod0_password_hist_len
Maximum password age: usrmod0_max_passwd_age
Minimum password age: usrmod0_min_passwd_age
Minimum password length: usrmod0_min_passwd_len
Password must meet complexity requirements: ?
Store passwords using reversible encryption:
I also know that WMI's RSOP ("Resultant set of policy") is unsuitable, as it only works on a domain. And i'm certainly not going to crawling through an undocumented binary blob (i.e. i want the supported way).
Note: I don't care about the "Store passwords using reversible encryption" group policy setting.
Bonus
You can also use the NetUserModalsGet API to retrieve the Account Lockout Policy settings:
Account lockout duration: usrmod3_lockout_duration
Account lockout threshold: usrmod3_lockout_threshold
Reset account lockout counter after: usrmod3_lockout_observation_window
Thus rounding out all the password related group policy options; except for "must meet complexity requirements".
For completeness, assume a non-domain joined machine (i.e. no AD server to query, no RSOP to query, etc).
This is accessible using SAM (Security Account Manager) APIs.
This API (served by SAMLIB.DLL) is not directly documented (no header, no SDK), but the "protocol" to use it is documented here: [MS-SAMR]: Security Account Manager (SAM) Remote Protocol (Client-to-Server), you "just" have to remove the r in described SamrXXXX methods.
The ones in question here are SamQueryInformationDomain (and associated SamSetInformationDomain) which will get you a DOMAIN_PASSWORD_INFORMATION structure
typedef struct _DOMAIN_PASSWORD_INFORMATION {
unsigned short MinPasswordLength;
unsigned short PasswordHistoryLength;
unsigned long PasswordProperties;
OLD_LARGE_INTEGER MaxPasswordAge;
OLD_LARGE_INTEGER MinPasswordAge;
} DOMAIN_PASSWORD_INFORMATION,
The PasswordProperties member can contain DOMAIN_PASSWORD_COMPLEX flag:
DOMAIN_PASSWORD_COMPLEX
0x00000001
The server enforces password complexity policy. See section 3.1.1.7.2 for details of the password policy.
I've provided some C# samples to check this.
First one dumps the policy for all domains served by the current machine's SAM server:
using (SamServer server = new SamServer(null, SamServer.SERVER_ACCESS_MASK.SAM_SERVER_ENUMERATE_DOMAINS | SamServer.SERVER_ACCESS_MASK.SAM_SERVER_LOOKUP_DOMAIN))
{
foreach (string domain in server.EnumerateDomains())
{
Console.WriteLine("domain: " + domain);
var sid = server.GetDomainSid(domain);
Console.WriteLine(" sid: " + sid);
var pi = server.GetDomainPasswordInformation(sid);
Console.WriteLine(" MaxPasswordAge: " + pi.MaxPasswordAge);
Console.WriteLine(" MinPasswordAge: " + pi.MinPasswordAge);
Console.WriteLine(" MinPasswordLength: " + pi.MinPasswordLength);
Console.WriteLine(" PasswordHistoryLength: " + pi.PasswordHistoryLength);
Console.WriteLine(" PasswordProperties: " + pi.PasswordProperties);
}
}
Second one reads and updates the policy for the current machine's domain:
using (SamServer server = new SamServer(null, SamServer.SERVER_ACCESS_MASK.SAM_SERVER_ALL_ACCESS))
{
var sid = server.GetDomainSid(Environment.MachineName);
var pi = server.GetDomainPasswordInformation(sid);
// remove password complexity
pi.PasswordProperties &= ~SamServer.PASSWORD_PROPERTIES.DOMAIN_PASSWORD_COMPLEX;
server.SetDomainPasswordInformation(sid, pi);
}
This is the SamServer utility:
public sealed class SamServer : IDisposable
{
private IntPtr _handle;
public SamServer(string name, SERVER_ACCESS_MASK access)
{
Name = name;
Check(SamConnect(new UNICODE_STRING(name), out _handle, access, IntPtr.Zero));
}
public string Name { get; }
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
SamCloseHandle(_handle);
_handle = IntPtr.Zero;
}
}
public void SetDomainPasswordInformation(SecurityIdentifier domainSid, DOMAIN_PASSWORD_INFORMATION passwordInformation)
{
if (domainSid == null)
throw new ArgumentNullException(nameof(domainSid));
var sid = new byte[domainSid.BinaryLength];
domainSid.GetBinaryForm(sid, 0);
Check(SamOpenDomain(_handle, DOMAIN_ACCESS_MASK.DOMAIN_WRITE_PASSWORD_PARAMS, sid, out IntPtr domain));
IntPtr info = Marshal.AllocHGlobal(Marshal.SizeOf(passwordInformation));
Marshal.StructureToPtr(passwordInformation, info, false);
try
{
Check(SamSetInformationDomain(domain, DOMAIN_INFORMATION_CLASS.DomainPasswordInformation, info));
}
finally
{
Marshal.FreeHGlobal(info);
SamCloseHandle(domain);
}
}
public DOMAIN_PASSWORD_INFORMATION GetDomainPasswordInformation(SecurityIdentifier domainSid)
{
if (domainSid == null)
throw new ArgumentNullException(nameof(domainSid));
var sid = new byte[domainSid.BinaryLength];
domainSid.GetBinaryForm(sid, 0);
Check(SamOpenDomain(_handle, DOMAIN_ACCESS_MASK.DOMAIN_READ_PASSWORD_PARAMETERS, sid, out IntPtr domain));
var info = IntPtr.Zero;
try
{
Check(SamQueryInformationDomain(domain, DOMAIN_INFORMATION_CLASS.DomainPasswordInformation, out info));
return (DOMAIN_PASSWORD_INFORMATION)Marshal.PtrToStructure(info, typeof(DOMAIN_PASSWORD_INFORMATION));
}
finally
{
SamFreeMemory(info);
SamCloseHandle(domain);
}
}
public SecurityIdentifier GetDomainSid(string domain)
{
if (domain == null)
throw new ArgumentNullException(nameof(domain));
Check(SamLookupDomainInSamServer(_handle, new UNICODE_STRING(domain), out IntPtr sid));
return new SecurityIdentifier(sid);
}
public IEnumerable<string> EnumerateDomains()
{
int cookie = 0;
while (true)
{
var status = SamEnumerateDomainsInSamServer(_handle, ref cookie, out IntPtr info, 1, out int count);
if (status != NTSTATUS.STATUS_SUCCESS && status != NTSTATUS.STATUS_MORE_ENTRIES)
Check(status);
if (count == 0)
break;
var us = (UNICODE_STRING)Marshal.PtrToStructure(info + IntPtr.Size, typeof(UNICODE_STRING));
SamFreeMemory(info);
yield return us.ToString();
us.Buffer = IntPtr.Zero; // we don't own this one
}
}
private enum DOMAIN_INFORMATION_CLASS
{
DomainPasswordInformation = 1,
}
[Flags]
public enum PASSWORD_PROPERTIES
{
DOMAIN_PASSWORD_COMPLEX = 0x00000001,
DOMAIN_PASSWORD_NO_ANON_CHANGE = 0x00000002,
DOMAIN_PASSWORD_NO_CLEAR_CHANGE = 0x00000004,
DOMAIN_LOCKOUT_ADMINS = 0x00000008,
DOMAIN_PASSWORD_STORE_CLEARTEXT = 0x00000010,
DOMAIN_REFUSE_PASSWORD_CHANGE = 0x00000020,
}
[Flags]
private enum DOMAIN_ACCESS_MASK
{
DOMAIN_READ_PASSWORD_PARAMETERS = 0x00000001,
DOMAIN_WRITE_PASSWORD_PARAMS = 0x00000002,
DOMAIN_READ_OTHER_PARAMETERS = 0x00000004,
DOMAIN_WRITE_OTHER_PARAMETERS = 0x00000008,
DOMAIN_CREATE_USER = 0x00000010,
DOMAIN_CREATE_GROUP = 0x00000020,
DOMAIN_CREATE_ALIAS = 0x00000040,
DOMAIN_GET_ALIAS_MEMBERSHIP = 0x00000080,
DOMAIN_LIST_ACCOUNTS = 0x00000100,
DOMAIN_LOOKUP = 0x00000200,
DOMAIN_ADMINISTER_SERVER = 0x00000400,
DOMAIN_ALL_ACCESS = 0x000F07FF,
DOMAIN_READ = 0x00020084,
DOMAIN_WRITE = 0x0002047A,
DOMAIN_EXECUTE = 0x00020301
}
[Flags]
public enum SERVER_ACCESS_MASK
{
SAM_SERVER_CONNECT = 0x00000001,
SAM_SERVER_SHUTDOWN = 0x00000002,
SAM_SERVER_INITIALIZE = 0x00000004,
SAM_SERVER_CREATE_DOMAIN = 0x00000008,
SAM_SERVER_ENUMERATE_DOMAINS = 0x00000010,
SAM_SERVER_LOOKUP_DOMAIN = 0x00000020,
SAM_SERVER_ALL_ACCESS = 0x000F003F,
SAM_SERVER_READ = 0x00020010,
SAM_SERVER_WRITE = 0x0002000E,
SAM_SERVER_EXECUTE = 0x00020021
}
[StructLayout(LayoutKind.Sequential)]
public struct DOMAIN_PASSWORD_INFORMATION
{
public short MinPasswordLength;
public short PasswordHistoryLength;
public PASSWORD_PROPERTIES PasswordProperties;
private long _maxPasswordAge;
private long _minPasswordAge;
public TimeSpan MaxPasswordAge
{
get
{
return -new TimeSpan(_maxPasswordAge);
}
set
{
_maxPasswordAge = value.Ticks;
}
}
public TimeSpan MinPasswordAge
{
get
{
return -new TimeSpan(_minPasswordAge);
}
set
{
_minPasswordAge = value.Ticks;
}
}
}
[StructLayout(LayoutKind.Sequential)]
private class UNICODE_STRING : IDisposable
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
public UNICODE_STRING()
: this(null)
{
}
public UNICODE_STRING(string s)
{
if (s != null)
{
Length = (ushort)(s.Length * 2);
MaximumLength = (ushort)(Length + 2);
Buffer = Marshal.StringToHGlobalUni(s);
}
}
public override string ToString() => Buffer != IntPtr.Zero ? Marshal.PtrToStringUni(Buffer) : null;
protected virtual void Dispose(bool disposing)
{
if (Buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(Buffer);
Buffer = IntPtr.Zero;
}
}
~UNICODE_STRING() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
private static void Check(NTSTATUS err)
{
if (err == NTSTATUS.STATUS_SUCCESS)
return;
throw new Win32Exception("Error " + err + " (0x" + ((int)err).ToString("X8") + ")");
}
private enum NTSTATUS
{
STATUS_SUCCESS = 0x0,
STATUS_MORE_ENTRIES = 0x105,
STATUS_INVALID_HANDLE = unchecked((int)0xC0000008),
STATUS_INVALID_PARAMETER = unchecked((int)0xC000000D),
STATUS_ACCESS_DENIED = unchecked((int)0xC0000022),
STATUS_OBJECT_TYPE_MISMATCH = unchecked((int)0xC0000024),
STATUS_NO_SUCH_DOMAIN = unchecked((int)0xC00000DF),
}
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamConnect(UNICODE_STRING ServerName, out IntPtr ServerHandle, SERVER_ACCESS_MASK DesiredAccess, IntPtr ObjectAttributes);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamCloseHandle(IntPtr ServerHandle);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamFreeMemory(IntPtr Handle);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamOpenDomain(IntPtr ServerHandle, DOMAIN_ACCESS_MASK DesiredAccess, byte[] DomainId, out IntPtr DomainHandle);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamLookupDomainInSamServer(IntPtr ServerHandle, UNICODE_STRING name, out IntPtr DomainId);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamQueryInformationDomain(IntPtr DomainHandle, DOMAIN_INFORMATION_CLASS DomainInformationClass, out IntPtr Buffer);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamSetInformationDomain(IntPtr DomainHandle, DOMAIN_INFORMATION_CLASS DomainInformationClass, IntPtr Buffer);
[DllImport("samlib.dll", CharSet = CharSet.Unicode)]
private static extern NTSTATUS SamEnumerateDomainsInSamServer(IntPtr ServerHandle, ref int EnumerationContext, out IntPtr EnumerationBuffer, int PreferedMaximumLength, out int CountReturned);
}

Resources