Example

CodeAccessPermission is an abstract class, see derived classes for more examples.

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

namespace Samples
{
  public class CodeAccessPermissionSample
  {
    public static void Main()
    {
      string ev = "USERNAME";
      EnvironmentPermission p =
             new EnvironmentPermission(
                     EnvironmentPermissionAccess.Read,
                     ev);
      p.Assert();
      TestAccess(ev);
      CodeAccessPermission.RevertAssert();
      p.Deny();
      TestAccess(ev);
      CodeAccessPermission.RevertDeny();
      p.PermitOnly();
      TestAccess(ev);
    }
    public static void TestAccess(string s)
    {
      try
      {
         Console.WriteLine("Variable {0} Value: {1}", s,
                 Environment.GetEnvironmentVariable(s));
      }
      catch(Exception)
      {
        Console.WriteLine("Variable {0} cannot be read", s);
      }
    }
  }
}
The output ...

Get .NET Framework Standard Library Annotated Reference, Volume 1: Base Class Library and Extended Numerics Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.