WriteFile to SD card (physical hard disk) fails with ERROR_ACCESS_DENIED (0x5)

skatz 1 Reputation point
2021-07-23T14:40:01.683+00:00

I'm trying to write to physical Hard Disk (SD Card/FAT32) directly using Windows API: WriteFile() but it always fails with ERROR_ACCESS_DENIED (0x5). I've tried many options suggested by some other posts such as unmount/lock but nothing seems to be working.

Does anyone have a better idea what is the root cause of this and how can we access to the physical drive directly from Windows API?

This is the sample code I'm using:

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <windows.h>

DWORD lastError;

int main (void) {
  uint16_t x, y;
  uint8_t  buffer[512];
  DWORD    bytesWritten, status;

  HANDLE sdCardHandle = CreateFile("\\\\.\\PhysicalDrive2", GENERIC_READ    | GENERIC_WRITE,
                                                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

  if(sdCardHandle == INVALID_HANDLE_VALUE) {
    CloseHandle(sdCardHandle);
    return -1;
  }

  for (y = 1; y < 10001; y++) { 
    memset(buffer, y, sizeof(buffer));
    if (WriteFile(sdCardHandle, buffer, sizeof(buffer), &bytesWritten, NULL) == 0) {
      lastError = GetLastError();
      printf("WriteFile error: 0x%X\n", lastError);
      CloseHandle(sdCardHandle);
      return -2;
    }
    printf("%d\n", y);
  }

  CloseHandle(sdCardHandle);
  return 0;
}

Thanks!

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,619 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,726 Reputation points Microsoft Vendor
    2021-07-26T01:59:43.597+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.