This post originated from an RSS feed registered with .NET Buzz
by -.
Original Post: Lese- und Schreibrechte einer Datei ��berpr��fen
Feed Title: Norbert Eder - Living .NET
Feed URL: http://feeds.feedburner.com/NorbertEder-Livingnet
Feed Description: Copyright (c)2005, 2006 by Norbert Eder
Kaum ein Entwickler ��berpr��ft bei Dateizugriffe, ob der aktuell angemeldete User auch tats��chlich ��ber die entsprechenden Rechte verf��gt. Hintergrund ist wohl, dass die meisten User mit einem Administrator-Account (was zumindest Windows betrifft) angemeldet sind. Hier eine einfache M��glichkeit, die Lese- bzw. Schreibrechte einer Datei abzufragen:
public class FileRightsReader
{
public static bool IsReadable(string filename)
{
WindowsIdentity principal = WindowsIdentity.GetCurrent();
if (File.Exists(filename))
{
FileInfo fi = new FileInfo(filename);
AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
for (int i = 0; i < acl.Count; i++)
{
System.Security.AccessControl.FileSystemAccessRule rule =
(System.Security.AccessControl.FileSystemAccessRule)acl;
if (principal.User.Equals(rule.IdentityReference))
{
if (System.Security.AccessControl.AccessControlType.Deny.Equals
(rule.AccessControlType))
{
if ((((int)FileSystemRights.Read) & (int)rule.FileSystemRights) == (int)(FileSystemRights.Read))
return false;
}
else if (System.Security.AccessControl.AccessControlType.Allow.Equals
(rule.AccessControlType))
{
if ((((int)FileSystemRights.Read) & (int)rule.FileSystemRights) == (int)(FileSystemRights.Read))
return true;
}
}
}
}
else
{
return false;
}
return false;
}
public static bool IsWriteable(string filename)
{
WindowsIdentity principal = WindowsIdentity.GetCurrent();
if (File.Exists(filename))
{
FileInfo fi = new FileInfo(filename);
if (fi.IsReadOnly)
return false;
AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
for (int i = 0; i < acl.Count; i++)
{
System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl;
if (principal.User.Equals(rule.IdentityReference))
{
if (System.Security.AccessControl.AccessControlType.Deny.Equals
(rule.AccessControlType))
{
if ((((int)FileSystemRights.Write) & (int)rule.FileSystemRights) == (int)(FileSystemRights.Write))
return false;
}
else if (System.Security.AccessControl.AccessControlType.Allow.Equals
(rule.AccessControlType))
{
if ((((int)FileSystemRights.Write) & (int)rule.FileSystemRights) == (int)(FileSystemRights.Write))
return true;
}
}
}