Couple of times I got a question to <Enable or Disable “Enable write caching on disk” behavior on disk>, How to do it programmatically on Windows? When I got this question for the first time, it was tough but doing research I was able to solve it and it works well. Every next time, it was easy :)
In this post, I will not discuss what exactly this feature does and pros and cons of enable/disable it. I will only discuss, How to do it.
You can do it manually as well.
#1, Select a volume from Explorer, right click –> Properties
#2, Select “Hardware” tab, select disk and click “Properties” button
#3, Select “Policies” tab.
#4, Check/Uncheck to enable/disable “write caching on the disk”
To do it programmatically.
#1, You will need to work with below APIs and control code.
IOCTL_DISK_GET_CACHE_INFORMATION Control Code
IOCTL_DISK_SET_CACHE_INFORMATION Control Code
The information is actually gets stored in below registry key, I would not recommend to look for the value in the key directly and design your application on that. It may change in future.
HKLM\SYSTEM\CurrentControlSet\Enum\IDE\Diskxxxxxxxxxxxx\DeviceParameters\Disk Key : UserWriteCacheSetting
where xxxxxxx is manufacturer information.
The sample will look like below. This is just a test sample and provided only to demonstrate the functionality. You might need to use put more error handling and test the code as you do for regular production environment code.
1: //////////////////////SAMPLE CODE
3: #define _WIN32_WINNT 0x0503
5: #include <windows.h>
7: DISK_CACHE_INFORMATION info;
8: DISK_CACHE_INFORMATION rinfo;
11: void main(void)
13: DWORD rr;
14: HANDLE hDevice;
15: DWORD err;
16: DWORD returned;
18: hDevice = CreateFile("\\\\.\\C:", // drive to open
19: GENERIC_READ | GENERIC_WRITE,
20: FILE_SHARE_WRITE | FILE_SHARE_READ,
21: // share mode
22: NULL, // default security attributes
23: OPEN_EXISTING, // disposition
24: FILE_ATTRIBUTE_SYSTEM, // file attributes
25: NULL); // do not copy file attributes
31: rr = DeviceIoControl(hDevice,IOCTL_DISK_GET_CACHE_INFORMATION,NULL,
32: 0,(LPVOID)&info,(DWORD)sizeof(info),(LPDWORD)&returned, (LPOVERLAPPED)NULL);
33: if (!rr)
35: err = GetLastError();
39: info.WriteCacheEnabled = true;
40: info.ReadCacheEnabled = false;
41: info.DisablePrefetchTransferLength = 1;
43: rr = DeviceIoControl(hDevice,IOCTL_DISK_SET_CACHE_INFORMATION,(LPVOID)&info,(DWORD)sizeof(info),
45: if (!rr)
47: err = GetLastError();
51: rr = DeviceIoControl(hDevice,IOCTL_DISK_GET_CACHE_INFORMATION,NULL,0,
53: if (!rr)
55: err = GetLastError();
61: //////////////////////SAMPLE CODE
*Note—Not all disks and controllers implements write disk caching, I have not tested the behavior or any such disk yet, so behavior is unknown to me.
Windows SDK - Microsoft