AFZAL KHAN AFZAL KHAN - 4 months ago 31x Question

SetAccessControl giving error as An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

I need to set access control to a folder

my code is

Private Sub cmdApplyRestrictions_Click(sender As Object, e As EventArgs) Handles cmdApplyRestrictions.Click
Dim myDirectoryInfo As New DirectoryInfo(txtFolder.Text)

Dim myDirectorySecurity As DirectorySecurity = myDirectoryInfo.GetAccessControl()
Dim User As String = System.Environment.UserDomainName + "\" + cmbUser.SelectedItem.ToString()

myDirectorySecurity.AddAccessRule(New FileSystemAccessRule(User, FileSystemRights.Read, AccessControlType.Deny))
MessageBox.Show("Permissions Altered Successfully")

End Sub

the line


is giving exception as

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

I am logged in as a user with administrative rights but not administrator itself
i need to block access to all users including the logged in user as well as all user including administrator

later when my program ends, i will to restore the permissions

One more requirement is that i wish to grant access to this folder one external program


You need your app to be executed with elevated privileges.

Add an app.manifest file to your app with this content:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="">
  <assemblyIdentity version="" name=""/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />