获取当前用户.net的文件权限

时间:2017-02-15 21:27:34

标签: c# .net file permissions directory-security

我正在扫描文件夹中的文件,我需要以任何方式将当前用户的每个文件权限表示为字符串。 因此,对于附加文件的属性,我想表示类似f-m-r-w的内容 字符串。

我正在尝试在我的扫描循环中完成此操作,但是获取空字符串。你能否暗示我应该从哪里出发或选择另一种方法?提前谢谢!

            string permissionShort = string.Empty;
            DirectorySecurity dSecurity = Directory.GetAccessControl(_directory.FullName);
            foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
            {
                if (rule.FileSystemRights == FileSystemRights.Write)
                    permissionShort = permissionShort + "x";
                if (rule.FileSystemRights == FileSystemRights.Read)
                    permissionShort = permissionShort + "x";
                if (rule.FileSystemRights == FileSystemRights.AppendData)
                    permissionShort = permissionShort + "x";
                if (rule.FileSystemRights == FileSystemRights.Modify)
                    permissionShort = permissionShort + "x";
                if (rule.FileSystemRights == FileSystemRights.ExecuteFile)
                    permissionShort = permissionShort + "x";
            }

1 个答案:

答案 0 :(得分:0)

FileSystemRights是一个标记的枚举,这意味着您必须执行AND操作来测试枚举的单个值。

    string scanPath = @"C:\Test";
    string permissionShort = string.Empty;
    DirectorySecurity dSecurity = Directory.GetAccessControl(scanPath);
    foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
    {
        permissionShort += rule.FileSystemRights.ToString() + " : ";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl) ? "f" : "-";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.Write)== FileSystemRights.Write) ? "w" : "-";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read) ? "r" : "-";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.AppendData) == FileSystemRights.AppendData) ? "a" : "-";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify) ? "m" : "-";
        permissionShort += ((rule.FileSystemRights & FileSystemRights.ExecuteFile) == FileSystemRights.ExecuteFile) ? "e" : "-";
        permissionShort += "\n";
    }