我想编写一段代码来检查共享目录的权限,我查看了多个解决方案,但当我尝试获取本地目录权限时,这些方案都能够正常工作,但是当我对共享目录进行测试时,它们就失败了。
我正在尝试这个问题中的示例: SOF: checking-for-directory-and-file-write-permissions-in-net,但它只能在本地目录上运行。
例如,我使用了这个类:
我正在尝试这个问题中的示例: 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);
}
WindowsIdentity.GetCurrent
的用户帐户名称。3. 请确认您已经尝试使用不同于自己的WindowIdentity进行测试,最简单的方法是https://dev59.com/KXVC5IYBdhLWcg3w-mdO#7250145。谢谢。 - Jeremy Thompson