- 1 year ago
How to delete a device node of disk by program
To delete a device node of a disk programmatically in Windows, you can use the SetupDi
functions from the Windows Setup API. The following steps outline the process:
Include the necessary headers:
cpp#include <Windows.h>
#include <SetupAPI.h>
Enumerate the disk devices:
Use theSetupDiGetClassDevs
function to retrieve a list of disk devices. Specify theGUID_DEVINTERFACE_DISK
interface class GUID to retrieve only disk devices.cppHDEVINFO deviceInfoSet = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (deviceInfoSet == INVALID_HANDLE_VALUE) {
// Error handling
return 1;
}
Find the device node of the target disk:
Use theSetupDiEnumDeviceInterfaces
andSetupDiGetDeviceInterfaceDetail
functions to iterate through the disk devices and retrieve the device path of the target disk. You may need to specify additional criteria to identify the specific disk you want to delete.cppSP_DEVINFO_DATA deviceInfoData = { sizeof(SP_DEVINFO_DATA) };
DWORD index = 0;
while (SetupDiEnumDeviceInfo(deviceInfoSet, index, &deviceInfoData)) {
// Retrieve the device path using SetupDiGetDeviceInterfaceDetail
// Additional logic to identify the target disk
// ...
index++;
}
Delete the device node:
Use theSetupDiRemoveDevice
function to delete the device node of the disk identified by the device path.cppSP_REMOVEDEVICE_PARAMS removeParams = { sizeof(SP_REMOVEDEVICE_PARAMS) };
removeParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
removeParams.Scope = DI_REMOVEDEVICE_GLOBAL;
removeParams.HwProfile = 0; // Use the current hardware profile
if (!SetupDiRemoveDevice(deviceInfoSet, &deviceInfoData)) {
// Error handling
return 1;
}
Cleanup and release resources:
After deleting the device node, clean up and release the resources obtained from the Setup API functions.cppSetupDiDestroyDeviceInfoList(deviceInfoSet);
Please note that the provided code is a simplified example, and you may need to handle errors, perform additional filtering or identification logic to pinpoint the target disk, and handle potential dependencies or consequences of deleting the device node. Also, remember to compile the code as a Windows application and link against the appropriate library (e.g., setupapi.lib
).
Modifying system configuration programmatically can have serious consequences, so exercise caution and thoroughly test your code before deploying it in a production environment.