Add file access rule : File Access Rule « File Directory Stream « C# / CSharp Tutorial






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

static class MainClass
{
    static void Main(string[] args)
    {
        FileStream stream = null;
        string fileName = "c:\\Test.txt";

        // Deny 'Everyone' access to the file
        FileSecurity fSecurity = File.GetAccessControl(fileName);
        fSecurity.AddAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.Read, AccessControlType.Deny));
        File.SetAccessControl(fileName, fSecurity);

        // Attempt to access file.
        try
        {
            stream = new FileStream(fileName, FileMode.Create);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception thrown: ");
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            stream.Close();
            stream.Dispose();
        }
    }
}








15.11.File Access Rule
15.11.1.Set File access rule
15.11.2.Add file access rule
15.11.3.Creating a new file with specific access rule