Search code examples
c++uac

filesystem:error cannot remove: Input/output error


I'm trying to delete a font file using this way,

std::filesystem::remove(std::filesystem::path("C:\\Windows\\Fonts\\segmdl2.ttf"));

But this fails and throw an exception,

filesystem:error cannot remove: Input/output error

The exception is not helpful. What's the correct way to delete this kind of files?

Update,

I made an attempt to delete it from Powershell and it throw following error,

del C:\Windows\Fonts\segmdl2.ttf
del : Cannot remove item C:\Windows\Fonts\segmdl2.ttf: Access to the path 'C:\Windows\Fonts\segmdl2.ttf' is denied.
At line:1 char:1
+ del C:\Windows\Fonts\segmdl2.ttf
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\Fonts\segmdl2.ttf:FileInfo) [Remove-Item], UnauthorizedAcc
   essException
    + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand

I even tried to remove it directly from font folder, I'm getting an error that it can't be done because an another application already using the font.

But I was successfully able to delete it from the command prompt.

How does cmd do this?

I need to achieve same level for my app.


Solution

  • The error happened because I don't have permission to delete the file and in some cases it happened because the file already opened by another process.

    To fix permission issue, I had to invoke the following commands from command promot,

    takeown /f C:\Windows\Fonts /r /d y
    icacls C:\Windows\Fonts /grant administrators:F /t
    

    To fix the issue when the file owned by another processs, I've found an application called IOBitUnlocker that capable of doing this without closing the processs so I decided to dig more into it.

    I've reverse engineered IOBitUnlocker. They are using a Kernel Mode Driver and uses KeStackAttachProcess to attach into the process that owns the file and unlock it.

    I am lucky enough to find an article with complete code that describe how to use this API to unlock the file.

    https://www.programmersought.com/article/96107379969/

    This method superior because you don't have to close the applications or reboot your machine. Altho, you have to sign the kernel mode driver or disable the driver validation directly from your BIOS.