Manipulate the Access Control List of a File or Directory - CSharp File IO

CSharp examples for File IO:Permission

Description

Manipulate the Access Control List of a File or Directory

Demo Code


using System;//w w w . ja  v  a  2  s.com
using System.IO;
using System.Security.AccessControl;

static class MainClass
{
    static void Main(string[] args)
    {
        FileStream stream;
        string fileName;

        fileName = Path.GetRandomFileName();
        using (stream = new FileStream(fileName, FileMode.Create))
        {
            // Do something.
        }
        Console.WriteLine("Created a new file " + fileName + ".");
        Console.WriteLine("Press any key to deny 'Everyone' " + "access to the file...");
        Console.ReadKey(true);
        SetRule(fileName, "Everyone", FileSystemRights.Read, AccessControlType.Deny);
        Console.WriteLine("Removed access rights of 'Everyone'.");
        Console.WriteLine("Press any key to attempt " + "access to the file...");
        try
        {
            stream = new FileStream(fileName, FileMode.Create);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception thrown: ");
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            stream.Close();
            stream.Dispose();
        }
    }

    static void AddRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
    {
        FileSecurity fSecurity = File.GetAccessControl(filePath);
        fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
        File.SetAccessControl(filePath, fSecurity);
    }

    static void SetRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
    {
        FileSecurity fSecurity = File.GetAccessControl(filePath);
        fSecurity.ResetAccessRule(new FileSystemAccessRule(account, rights, controlType));
        File.SetAccessControl(filePath, fSecurity);
    }

}

Result


Related Tutorials