取得文件夹是否有用户

/// <summary>
        /// 取得文件夹是否有用户
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        internal static bool HasOperationPermission(string filePath, string userName = "")
        {
            if(string.IsNullOrWhiteSpace(userName))
            {
                userName = Environment.UserName;
            }
           
            bool accessRule = false;
            var sysAccessRule = GetFileSysAccessRule(filePath);
            var groupMem = GetWindowUserGroup();
            var groupList = new List<string>();
            foreach (var item in groupMem.ToList())
            {
                if (item.Value.Contains(userName))
                {
                    //var groupName = Path.Combine(Environment.MachineName, item.Key);
                    groupList.Add(item.Key);
                }
            }
            
            var userAccessRules = sysAccessRule.Where(t => groupList.Contains(t.IdentityReference.Value.Split(@"").LastOrDefault())
                                     || t.IdentityReference.Value.Split(@"").LastOrDefault() == userName);
            var rezDeny = userAccessRules.Any(i => i.AccessControlType == AccessControlType.Deny);
            if (rezDeny)
            {
                accessRule = false;
            }
            var accessCount = userAccessRules.Count(i => (i.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify
                                                           || i.FileSystemRights == FileSystemRights.FullControl);
            if (accessCount > 0)
            {
                accessRule = true;
            }
            return accessRule;
        }

  

 static List<FileSystemAccessRule> GetFileSysAccessRule(string filePath)
        {

            DirectoryInfo dInfo = new DirectoryInfo(filePath);

            // Get a DirectorySecurity object that represents the
            // current security settings.
            DirectorySecurity fileAcl = dInfo.GetAccessControl();

            List<FileSystemAccessRule> userAccessRules = fileAcl.GetAccessRules(true, true, typeof(NTAccount))
                .OfType<FileSystemAccessRule>().ToList();

            return userAccessRules;
            // return userAccessRules.Any(i => i.AccessControlType == AccessControlType.Deny);
        }

  

 static Dictionary<string, List<string>> GetWindowUserGroup()
        {
            int LOCALGROUP_MEMBERS_INFO_1_SIZE;
            int LOCALGROUP_INFO_1_SIZE;
            LOCALGROUP_INFO_1_SIZE = Marshal.SizeOf(new Win32API.LOCALGROUP_INFO_1());
            LOCALGROUP_MEMBERS_INFO_1_SIZE = Marshal.SizeOf(new Win32API.LOCALGROUP_MEMBERS_INFO_1());
            Dictionary<string, List<string>> GroupMem = new Dictionary<string, List<string>>();
            //defining values for getting group names
            uint level = 1, prefmaxlen = 0xFFFFFFFF, entriesread = 0, totalentries = 0;

            //Values that will receive information.
            IntPtr GroupInfoPtr, UserInfoPtr;
            GroupInfoPtr = IntPtr.Zero;
            UserInfoPtr = IntPtr.Zero;

            Win32API.NetLocalGroupEnum(
                IntPtr.Zero, //Server name.it must be null
                level,//level can be 0 or 1 for groups.For more information see LOCALGROUP_INFO_0 and LOCALGROUP_INFO_1
                ref GroupInfoPtr,//Value that will be receive information
                prefmaxlen,//maximum length
                ref entriesread,//value that receives the count of elements actually enumerated. 
                ref totalentries,//value that receives the approximate total number of entries that could have been enumerated from the current resume position.
                IntPtr.Zero);

            //this string array will hold comments of each group
            var commentArray = new string[totalentries];

            //int LOCALGROUP_INFO_1_SIZE = Marshal.SizeOf(new Win32API.LOCALGROUP_INFO_1());
            // int LOCALGROUP_MEMBERS_INFO_1_SIZE = Marshal.SizeOf(new Win32API.LOCALGROUP_MEMBERS_INFO_1());


            //getting group names and add them to tree view
            for (int i = 0; i < totalentries; i++)
            {
                var userList = new List<string>();
                //converting unmanaged code to managed codes with using Marshal class 
                var groupPtr = GroupInfoPtr.ToInt64();
                long newOffset = groupPtr + LOCALGROUP_INFO_1_SIZE * i;
                // int newOffset = GroupInfoPtr.ToInt32() + LOCALGROUP_INFO_1_SIZE * i;
                Win32API.LOCALGROUP_INFO_1 groupInfo = (Win32API.LOCALGROUP_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset), typeof(Win32API.LOCALGROUP_INFO_1));
                string currentGroupName = Marshal.PtrToStringAuto(groupInfo.lpszGroupName);
                //storing group comment in an string array to show it in a label later
                commentArray[i] = Marshal.PtrToStringAuto(groupInfo.lpszComment);

                //defining value for getting name of members in each group
                uint prefmaxlen1 = 0xFFFFFFFF, entriesread1 = 0, totalentries1 = 0;

                //paramaeters for NetLocalGroupGetMembers is like NetLocalGroupEnum.
                Win32API.NetLocalGroupGetMembers(IntPtr.Zero, groupInfo.lpszGroupName, 1, ref UserInfoPtr, prefmaxlen1, ref entriesread1, ref totalentries1, IntPtr.Zero);

                //getting members name
                for (int j = 0; j < totalentries1; j++)
                {
                    //converting unmanaged code to managed codes with using Marshal class 
                    long newOffset1 = UserInfoPtr.ToInt64() + LOCALGROUP_MEMBERS_INFO_1_SIZE * j;
                    Win32API.LOCALGROUP_MEMBERS_INFO_1 memberInfo = (Win32API.LOCALGROUP_MEMBERS_INFO_1)Marshal.PtrToStructure(new IntPtr(newOffset1), typeof(Win32API.LOCALGROUP_MEMBERS_INFO_1));
                    string currentUserName = Marshal.PtrToStringAuto(memberInfo.lgrmi1_name);
                    //adding member name to tree view
                    userList.Add(currentUserName);
                }
                //free memory
                Win32API.NetApiBufferFree(UserInfoPtr);
                GroupMem.Add(currentGroupName, userList);

            }
            //free memory
            Win32API.NetApiBufferFree(GroupInfoPtr);
            return GroupMem;
        }

  

原文地址:https://www.cnblogs.com/robertyao/p/14776232.html