Delete file from C:\Program Files (x86)\"Folder Name"\"File Name" is Denied

Frangky Bunga 41 Reputation points
2023-10-25T01:34:46.1566667+00:00

Hi All,

Please help.

I want to delete a file and an error message appears: Some or all identity references could not be translated.Screenshot_4

 Dim UserAccount As String = System.Windows.Forms.SystemInformation.UserName
        Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo("C:\Program Files (x86)\FastCodeSDK")
        Dim FolderAcl As New DirectorySecurity
        FolderAcl.AddAccessRule(New FileSystemAccessRule(UserAccount, FileSystemRights.Modify, InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow))
        FolderInfo.SetAccessControl(FolderAcl)

        File.Delete("C:\Program Files (x86)\FastCodeSDK\Data1.cab")

        MsgBox("the file has been deleted")

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,668 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 29,261 Reputation points Microsoft Vendor
    2023-10-25T08:12:55.98+00:00

    Hi @Frangky Bunga ,

    This error is usually caused by trying to set an access control list using incorrect user identifiers (identity references).

    You can try converting the user name to a security identifier (SID) and then passing it to the FileSystemAccessRule constructor.

    This ensures that you are using a valid security identifier, regardless of whether the current user is a local user or a domain user. Using SIDs avoids errors caused by incorrect user name formatting or non-existent users.

    Also as RLWA32 mentioned, make sure that the current user has permission to modify ACLs.

    Dim UserAccountSid As SecurityIdentifier = New NTAccount(UserAccount).Translate(GetType(SecurityIdentifier))
    
    Dim FolderAcl As New DirectorySecurity
    FolderAcl.AddAccessRule(New FileSystemAccessRule(UserAccountSid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow))
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.