Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

59 rader
2.5 KiB

  1. using Alphaleonis.Win32.Filesystem;
  2. using System.Collections.Generic;
  3. using System.Security.AccessControl;
  4. using System.Security.Principal;
  5. namespace Security2
  6. {
  7. public partial class FileSystemAccessRule2
  8. {
  9. public static IEnumerable<FileSystemAccessRule2> GetFileSystemAccessRules(FileSystemInfo item, bool includeExplicit, bool includeInherited, bool getInheritedFrom = false)
  10. {
  11. var sd = new FileSystemSecurity2(item, AccessControlSections.Access);
  12. return GetFileSystemAccessRules(sd, includeExplicit, includeInherited, getInheritedFrom);
  13. }
  14. public static IEnumerable<FileSystemAccessRule2> GetFileSystemAccessRules(FileSystemSecurity2 sd, bool includeExplicit, bool includeInherited, bool getInheritedFrom = false)
  15. {
  16. List<FileSystemAccessRule2> aceList = new List<FileSystemAccessRule2>();
  17. List<string> inheritedFrom = null;
  18. if (getInheritedFrom)
  19. {
  20. inheritedFrom = Win32.GetInheritedFrom(sd.Item, sd.SecurityDescriptor);
  21. }
  22. var aceCounter = 0;
  23. var acl = !sd.IsFile ?
  24. ((DirectorySecurity)sd.SecurityDescriptor).GetAccessRules(includeExplicit, includeInherited, typeof(SecurityIdentifier)) :
  25. ((FileSecurity)sd.SecurityDescriptor).GetAccessRules(includeExplicit, includeInherited, typeof(SecurityIdentifier));
  26. foreach (FileSystemAccessRule ace in acl)
  27. {
  28. var ace2 = new FileSystemAccessRule2(ace) { FullName = sd.Item.FullName, InheritanceEnabled = !sd.SecurityDescriptor.AreAccessRulesProtected };
  29. if (getInheritedFrom)
  30. {
  31. ace2.inheritedFrom = string.IsNullOrEmpty(inheritedFrom[aceCounter]) ? "" : inheritedFrom[aceCounter].Substring(0, inheritedFrom[aceCounter].Length - 1);
  32. aceCounter++;
  33. }
  34. aceList.Add(ace2);
  35. }
  36. return aceList;
  37. }
  38. public static IEnumerable<FileSystemAccessRule2> GetFileSystemAccessRules(string path, bool includeExplicit, bool includeInherited, bool getInheritedFrom = false)
  39. {
  40. if (File.Exists(path))
  41. {
  42. return GetFileSystemAccessRules(new FileInfo(path), includeExplicit, includeInherited, getInheritedFrom);
  43. }
  44. else
  45. {
  46. return GetFileSystemAccessRules(new DirectoryInfo(path), includeExplicit, includeInherited, getInheritedFrom);
  47. }
  48. }
  49. }
  50. }