Search
Desktop

Get File Security Description

Published 1 min readBy Programming4us Editorial Team
Problem : You want to retrieve security information for a file. Security descriptors can be attached to many types of objects, but some of the most common to deal with are files.

Solution: The System.Security namespace contains .NET classes related to security. The following code sample display security information about a file whose name is passed on the command line.

using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace ShowFileSecurity
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: ShowFileSecurity filename");
return;
}
string filename = args[0];
FileInfo info = new FileInfo(filename);
FileSecurity security = info.GetAccessControl();
ShowSecurity(security);
}

private static void ShowSecurity(FileSecurity security)
{
AuthorizationRuleCollection coll =
security.GetAccessRules(true, true, typeof(NTAccount));
foreach (FileSystemAccessRule rule in coll)
{
Console.WriteLine("IdentityReference: {0}",
rule.IdentityReference);
Console.WriteLine("Access control type: {0}",
rule.AccessControlType);
Console.WriteLine("Rights: {0}", rule.FileSystemRights);
Console.WriteLine("Inherited? {0}", rule.IsInherited);

Console.WriteLine();
}
}
}
}


You can run the program from the command line like this:

D:\code\ch11\ShowFileSecurity\bin\Debug>ShowFileSecurity.exe ShowFileSecurity.pdb

It produces output similar to the following:
IdentityReference: Ben-Desktop\Ben
Access control type: Allow
Rights: FullControl
Inherited? True

IdentityReference: NT AUTHORITY\SYSTEM
Access control type: Allow
Rights: FullControl
Inherited? True
IdentityReference: BUILTIN\Administrators
Access control type: Allow
Rights: FullControl
Inherited? True