Search code examples
c#vb.netpermissionsdirectoryaccess-control

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))
    myDirectoryInfo.SetAccessControl(myDirectorySecurity)
    MessageBox.Show("Permissions Altered Successfully")

End Sub 

the line

myDirectoryInfo.SetAccessControl(myDirectorySecurity)

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


Solution

  • 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="http://www.w3.org/2001/XMLSchema-instance">
      <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
          <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
          </requestedPrivileges>
        </security>
      </trustInfo>
    </asmv1:assembly>