PermissionSet Class in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The PermissionSet class represents a collection of different permissions and supports the methods that use and modify those permissions. You can add, remove, assert, deny, and copy permissions. 

The example in Listing 22.20 uses the PermissionSet class to obtain the permissions necessary to gain full access to a file and to read a TEMP environment variable. Before changing the permissions of a file, the file will have a default permission set. 

The Deny method of the PermissionSet prevents callers from accessing the protected resource even if they have been granted permission to access it. The PermitOnly method of the PermissionSet ensures that only the resources specified by this permission object can be accessed, even if the code has been granted permission to other resources. FileIOPermissionAccess specifies the actions that can be performed on the file or folder. The EnvironmentPermission class instance, added to the PermissionSet in Listing 22.20, manages access to user and system environment variables by granting permissions on how a user queries and modifies user and system environment variables. 

Listing 22.20: PermissionSet Sample1 

using System;
using System.IO;
using System.Security.Permissions;
using System.Security;

public class TestClass
{
    public static void Main()
    {
        // Try to access resources using the permissions
        // currently available.
        AttemptAccess("Default permissions");

        // Create a permission set that allows read access to
        // the TEMP
        // environment variable and read, write, and append
        // access to C:\myfile.txt
        PermissionSet ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP"));
        ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read |
        FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, @"c:\myfile.txt"));

        // test if we can access the resource contained in ps
        ps.Assert();

        // Try to access resources using the permissions we've
        // just asserted.
        AttemptAccess("Assert permissions.");

        // Remove this stack frame's Assert
        CodeAccessPermission.RevertAssert();

        // Deny access to the resources we specify
        ps.Deny();

        // Try to access resources using the permissions we've
        // just denied.
        AttemptAccess("Deny permissions.");

        // Remove this stack frame's Deny so we're back to
        // default permissions.
        CodeAccessPermission.RevertDeny();

        // Make the permissions indicate the only things that
        // we're allowed to do.
        ps.PermitOnly();

        // Try to access resources using only the permissions
        // we've just permitted.
        AttemptAccess("PermitOnly permissions.");

        // Remove this stack frame's PermitOnly so we're back
        // to default permissions.
        CodeAccessPermission.RevertPermitOnly();

        // Remove the FileIOPermissions from the permission set
        ps.RemovePermission(typeof(FileIOPermission));

        // Try to access resources using only the Environment
        // permissions.
        ps.PermitOnly();
        AttemptAccess("PermitOnly without FileIOPermission permissions.");

        // Remove this stack frame's PermitOnly so we're back
        // to default permissions.
        CodeAccessPermission.RevertPermitOnly();

        // Remove the EnvironmentPermission from the permission
        // set
        ps.RemovePermission(typeof(EnvironmentPermission));

        // Try to access resources using no permissions.
        ps.PermitOnly();
        AttemptAccess("PermitOnly without any permissions");

        // Remove this stack frame's PermitOnly so we're back
        // to default permissions.
        CodeAccessPermission.RevertPermitOnly();
        Console.ReadLine();
    }

    public static void AttemptAccess(String strMsg)
    {
        Console.WriteLine(strMsg);
        FileStream fs = null;
        String env = null;

        // Try to access a file
        try
        {
            fs = new FileStream("SomeFile", FileMode.OpenOrCreate);
        }

        catch (Exception)
        {
            // ignore catch
        }

        // Try to read an environment variable
        try
        {
            env = Environment.GetEnvironmentVariable("TEMP");
        }

        catch (Exception)
        {
            // ignore catch
        }

        // Display what we sucessfully did and what we failed.
        Console.WriteLine("test results: " + ((fs != null) ?
        "File opened." :
        "File cannot be opened!") + " " +
        ((env != null) ? "Environment read." :
        "Environment cannot be read!"));

        // close file stream
        if (fs != null)
        {
            fs.Close();
        }
    }
}

Figure 22.8 contains the output created by the various access attempts in Listing 22.20. 

Figure-22.8.gif

Figure 22.8: Output Generated by Listing 22.20 

Listing 22.21 first denies permissions to the permission set it has created. Then it uses the RevertDeny method to allow access again.

Listing 22.21: PermissionSet Sample2, RevertDeny 

    // RevertDeny
    public interface anyinterface
    {
        void anyfunction(char ch1);
    }

    public class myclass:anyinterface
    {
        PermissionSet ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new
        FileIOPermission(FileIOPermissionAccess.AllAccess,@"c:\dir1"));
        ps.AddPermission(new
        FileIOPermission(FileIOPermissionAccess.AllAccess, @"c:\dir2"));
        ps.AddPermission(new
        EnvironmentPermission(PermissionState.Unrestricted));

        // deny the permissions we just created
        ps.Deny();
        anyfunction('a');
        // revoke denial of the permissions just created
        CodeAccessPermission.RevertDeny();
    }

Conclusion

Hope this article would have helped you in understanding PermissionSet Class in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all