【发布时间】:2016-01-20 11:24:27
【问题描述】:
我想编写一个检查共享目录权限的代码,我检查了多个解决方案,但它在尝试获取本地目录权限时效果很好,但是当我为共享目录创建测试用例时它失败了。
我在这个问题中尝试示例: SOF: checking-for-directory-and-file-write-permissions-in-net
但它仅适用于本地目录。
例如,我使用了这个类:
public class CurrentUserSecurity
{
WindowsIdentity _currentUser;
WindowsPrincipal _currentPrincipal;
public CurrentUserSecurity()
{
_currentUser = WindowsIdentity.GetCurrent();
_currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
}
public bool HasAccess(DirectoryInfo directory, FileSystemRights right)
{
// Get the collection of authorization rules that apply to the directory.
AuthorizationRuleCollection acl = directory.GetAccessControl()
.GetAccessRules(true, true, typeof(SecurityIdentifier));
return HasFileOrDirectoryAccess(right, acl);
}
public bool HasAccess(FileInfo file, FileSystemRights right)
{
// Get the collection of authorization rules that apply to the file.
AuthorizationRuleCollection acl = file.GetAccessControl()
.GetAccessRules(true, true, typeof(SecurityIdentifier));
return HasFileOrDirectoryAccess(right, acl);
}
private bool HasFileOrDirectoryAccess(FileSystemRights right,
AuthorizationRuleCollection acl)
{
bool allow = false;
bool inheritedAllow = false;
bool inheritedDeny = false;
for (int i = 0; i < acl.Count; i++)
{
FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[i];
// If the current rule applies to the current user.
if (_currentUser.User.Equals(currentRule.IdentityReference) ||
_currentPrincipal.IsInRole(
(SecurityIdentifier)currentRule.IdentityReference))
{
if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
{
if ((currentRule.FileSystemRights & right) == right)
{
if (currentRule.IsInherited)
{
inheritedDeny = true;
}
else
{ // Non inherited "deny" takes overall precedence.
return false;
}
}
}
else if (currentRule.AccessControlType
.Equals(AccessControlType.Allow))
{
if ((currentRule.FileSystemRights & right) == right)
{
if (currentRule.IsInherited)
{
inheritedAllow = true;
}
else
{
allow = true;
}
}
}
}
}
if (allow)
{ // Non inherited "allow" takes precedence over inherited rules.
return true;
}
return inheritedAllow && !inheritedDeny;
}
}
它检查当前模拟目录或文件的权限。 检查本地目录时所有测试用例都正确通过,但其中一些在共享目录中失败,这是我要解决的问题,那么有什么解决方案吗?
尽管目录没有写权限,但以下测试用例失败:
[TestMethod]
public void HasAccess_NotHaveAccess_ReturnsFalse()
{
CurrentUserSecurity cus = new CurrentUserSecurity();
bool result = cus.HasAccess(new DirectoryInfo(@"\\sharedpc\readonly"), System.Security.AccessControl.FileSystemRights.Write);
Assert.AreEqual(result, false);
}
【问题讨论】:
-
嗨,deserthero,我试过你的代码,这里一切正常。您确定在“\\sharedpc\readonly”文件夹中为当前用户设置了适当的权限吗?
-
嗨,我在下面给出了答案,但认为这是环境问题或只是有点混乱。我了解您的 TestMethod 返回 True 表示用户是否拥有权限,但这是不正确? 1.您能否edit您的问题并提供文件夹权限的屏幕截图以及 2.指出运行代码
WindowsIdentity.GetCurrent的用户帐户名。 3. 请确认您已经在自己旁边使用不同的 WindowIdentity 进行了测试,这是一种最简单的方法stackoverflow.com/questions/125341/… 谢谢。 -
你试过了吗,msdn.microsoft.com/en-us/library/…? Get 方法可能无法解析嵌套规则或依赖规则,例如应用于组的规则等,此方法可能会给您实际的访问规则进行验证。
标签: c# .net winforms acl access-control