1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
public bool CanReadDirectory(string path, WindowsIdentity account)
{
DirectorySecurity dirSec = null;
try
{
dirSec = Directory.GetAccessControl(path);
}
catch (UnauthorizedAccessException)
{
return false;
}
var rules = dirSec.GetAccessRules(true, true, typeof(NTAccount));
WindowsPrincipal wp = new WindowsPrincipal(account);
foreach (FileSystemAccessRule rule in rules)
{
if (wp.IsInRole(rule.IdentityReference.Value))
{
if ((rule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
return true;
}
}
return false;
}
public bool CanWriteDirectory(string path, WindowsIdentity account)
{
DirectorySecurity dirSec = null;
try
{
dirSec = Directory.GetAccessControl(path);
}
catch (UnauthorizedAccessException)
{
return false;
}
var rules = dirSec.GetAccessRules(true, true, typeof(NTAccount));
WindowsPrincipal wp = new WindowsPrincipal(account);
foreach (FileSystemAccessRule rule in rules)
{
if (wp.IsInRole(rule.IdentityReference.Value))
{
if ((rule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write)
return true;
}
}
return false;
}
public Test()
{
WindowsIdentity account = System.Security.Principal.WindowsIdentity.GetCurrent();
MessageBox.Show(CanReadDirectory("C:\\", account).ToString() + " " + CanWriteDirectory("C:\\", account).ToString());
MessageBox.Show(CanReadDirectory("D:\\td", account).ToString() + " " + CanWriteDirectory("D:\\td", account).ToString());
MessageBox.Show(CanReadDirectory("C:\\MSOCache", account).ToString() + " " + CanWriteDirectory("C:\\MSOCache", account).ToString());
} |
Partager