读取某个用户的文件夹权限\

时间:2014-03-06 14:28:56

标签: c# permissions directory

如何获取具有以下名称格式的用户的目录的写权限HOST \ UerName

我试过这个但是没有用

        DirectoryInfo di = new DirectoryInfo(path);
        DirectorySecurity acl = di.GetAccessControl();
        AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
        //Go through the rules returned from the DirectorySecurity
        foreach (AuthorizationRule rule in rules)
        {
            //If we find one that matches the identity we are looking for
            if (user_name == rule.IdentityReference.Value)) //(rule.IdentityReference.ToString().Contains(NtAccountName))
            {
                //Cast to a FileSystemAccessRule to check for access rights
                if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
                {
                   up.write = true;
                }

                if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Read) > 0)
                {
                    up.read = true;
                }


                if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.ExecuteFile) > 0)
                {
                    up.execute = true;
                }

                if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Delete) > 0)
                {
                    up.delete = true;
                }

            }
        }

1 个答案:

答案 0 :(得分:0)

我这样做。当然,这意味着运行它的用户有权更改ACL

 DirectoryInfo dInfo = new DirectoryInfo(dir);
 FileSystemAccessRule acl = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, FileSystemRights.FullControl, AccessControlType.Allow);

 if (dInfo.Exists)
 {
     DirectorySecurity ds = dInfo.GetAccessControl();
     ds.AddAccessRule(acl);
     dInfo.SetAccessControl(ds);
 }

模仿其他用户

 [DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr phToken);

int LOGON32_PROVIDER_DEFAULT = 0
int LOGON32_LOGON_INTERACTIVE = 2


IntPtr userToken = IntPtr.Zero;
bool success = LogonUser(
  "Username", 
  "Domain Name", 
  "Password", 
  LOGON32_LOGON_INTERACTIVE,
  LOGON32_PROVIDER_DEFAULT,
  out userToken);

if (!success)
{
  throw new SecurityException("Logon user failed");
}

using (WindowsIdentity.Impersonate(userToken))
{
  // do the stuff as user
}