c# 检测目录是否包含读写权限

 public static bool DirectoryHasPermission(string dirPath)
{
    bool result = false;
    try
    {
        var tempFile = dirPath.TrimEnd('\\') + @"\" + GUIDHelper.NewGuid;
        File.WriteAllText(tempFile, string.Empty);
        File.ReadAllText(tempFile);
        File.Delete(tempFile);

        result = true;
    }
    catch (System.Exception)
    {
    }

    return result;
}

/// <summary>
/// 检测目录是否包含指定的权限
/// </summary>
/// <param name="dirPath"></param>
/// <param name="AccessRight"></param>
/// <returns></returns>
public static bool DirectoryHasPermissionACL(string dirPath, FileSystemRights AccessRight)
        {
            try
            {
                AuthorizationRuleCollection rules = Directory.GetAccessControl(dirPath).GetAccessRules(true, true, typeof(NTAccount));

                //WindowsIdentity.GetCurrent() 返回的是当前​​线程​​的身份
                //WindowsIdentity identity = WindowsIdentity.GetCurrent();
                // 明确获取进程级身份(即使线程在模拟)
                WindowsIdentity identity = WindowsIdentity.GetCurrent(false);
                // 检查当前是否在模拟状态
                if (identity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)
                {
                    identity = WindowsIdentity.GetCurrent(true); // 获取线程身份
                }

                bool hasExplicitDeny = false;
                bool hasExplicitAllow = false;

                foreach (FileSystemAccessRule rule in rules)
                {
                    if (rule.IdentityReference.Value == identity.Name ||
                        identity.Groups.Contains(rule.IdentityReference))
                    {
                        //if ((rule.FileSystemRights & AccessRight) == AccessRight)
                        if (rule.FileSystemRights.HasFlag(AccessRight))
                        {
                            //优先判断明确拒绝的权限
                            if (rule.AccessControlType == AccessControlType.Deny)
                            {
                                hasExplicitDeny = true;
                            }
                            else if (rule.AccessControlType == AccessControlType.Allow)
                            {
                                hasExplicitAllow = true;
                            }
                        }
                    }
                }
                return hasExplicitAllow && !hasExplicitDeny;

            }
            catch { }
            return false;
        }
posted @ 2025-04-08 14:30  Hey,Coder!  阅读(31)  评论(0)    收藏  举报