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;
}
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com