Windows安全机制学习笔记(五)-枚举文件ACL

使用FileSecurity类和FileInfo类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace GetFileAcls
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "c:\\testFile.txt";
            using (FileStream fStream = File.Create(fileName))
            {
                StreamWriter writer = new StreamWriter(fStream);
                writer.WriteLine("This is a test file.");
                writer.Close();
            }

            FileInfo fInfo = new FileInfo(fileName);
            FileSecurity fileAcl = fInfo.GetAccessControl();
            NTAccount acc = (NTAccount)fileAcl.GetOwner(typeof(NTAccount));
            Console.WriteLine("File owner:" + acc.Value);
            AuthorizationRuleCollection authRules =  fileAcl.GetAccessRules(true, true, typeof(NTAccount));
            Console.WriteLine("File access rules:");
            Console.ForegroundColor= ConsoleColor.Red;
            foreach (AuthorizationRule item in authRules)
            {
                FileSystemAccessRule rule = (FileSystemAccessRule)item;
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append("IsInherited:" + rule.IsInherited + "\t");
                strBuilder.Append("Inheritance flags:" + rule.InheritanceFlags.ToString() + "\t");
                strBuilder.Append("Propagation flags:" + rule.PropagationFlags + "\t");
                NTAccount ntAcc = (NTAccount)rule.IdentityReference.Translate(typeof(NTAccount));
                strBuilder.Append("Account name:" + ntAcc.Value + "\t");
                strBuilder.Append("Access flags:" + rule.FileSystemRights.ToString());
                strBuilder.Append("Access type:" + rule.AccessControlType.ToString());
                Console.WriteLine(strBuilder.ToString());
            }
            Console.ResetColor();
        }
    }
}

 

posted @ 2013-07-12 13:38  Mr..Hu  阅读(562)  评论(0编辑  收藏  举报