SetAccessControl给出错误,因为mscorlib.dll中发生了'System.UnauthorizedAccessException'类型的未处理异常

时间:2016-06-02 02:58:07

标签: c# vb.net permissions directory access-control

我需要将访问控制设置为文件夹

我的代码是

 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 

myDirectoryInfo.SetAccessControl(myDirectorySecurity)

将异常视为

mscorlib.dll中出现未处理的“System.UnauthorizedAccessException”类型异常

我以具有管理权限但不是管理员本身的用户身份登录 我需要阻止访问所有用户,包括登录用户以及包括管理员在内的所有用户

稍后当我的程序结束时,我将恢复权限

还有一个要求是我希望授予对此文件夹一个外部程序的访问权限

1 个答案:

答案 0 :(得分:1)

您需要使用提升的权限执行您的应用。

使用以下内容向您的应用添加app.manifest文件:

<?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>