Esta documentación está archivada y no tiene mantenimiento.

NamedPermissionSet (Clase)

Actualización: noviembre 2007

Define un conjunto de permisos que tiene un nombre y una descripción asociada. No se puede heredar esta clase.

Espacio de nombres:  System.Security
Ensamblado:  mscorlib (en mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class NamedPermissionSet : PermissionSet
/** @attribute SerializableAttribute */ 
/** @attribute ComVisibleAttribute(true) */
public final class NamedPermissionSet extends PermissionSet
public final class NamedPermissionSet extends PermissionSet

Los conjuntos de permisos con nombre se utilizan en la administración de directivas de seguridad para especificar los permisos que se concederán al código que pertenece a determinados grupos de códigos. Los nombres son cadenas de caracteres alfanuméricos. Las cadenas de descripción pueden contener cualquier carácter imprimible. Para obtener más información, vea Conjuntos de permisos con nombre.

En el siguiente ejemplo de código se muestra el uso de miembros de la clase NamedPermissionSet.

using System;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.IO;
using System.Collections;

class NamedPermissionSetDemo
{
    public static void PermissionSetDemo()
    {
        Console.WriteLine("Executing NamedPermissionSetDemo");
        try
        {
          // Create a new named permission set and add it to Machine policy.
            NamedPermissionSet namedPS1 = CreateCompanyPermission();
            Console.WriteLine("The name of the custom named permission set is " + namedPS1.Name + "\n");
            Console.WriteLine("The description of the custom named permission set is " + namedPS1.Description + "\n");
            DisplayPermissions(namedPS1);
            NamedPermissionSet namedPS2 = new NamedPermissionSet("MyPermssionSetCopy");
            // Perform a ToXml/FromXml round trip.
            namedPS2.FromXml(namedPS1.ToXml());
            Console.WriteLine("\nResult of the ToXml/FromXml round trip:");

            // For simplicity the results are displayed using a method call.
            DisplayPermissions(namedPS2);

            // Create and display a copy of a permission set.
            NamedPermissionSet namedPS3 = (NamedPermissionSet)namedPS2.Copy();
            Console.WriteLine("Is the copy equal to the original? " + namedPS2.Equals(namedPS3));
            NamedPermissionSet namedPS4 = new NamedPermissionSet("Second copy", namedPS3);
            Console.WriteLine("The name of the new permission set is " + namedPS4.Name + "\n");
            // Show that the new named permission set has the same permissions as the original.
            DisplayPermissions(namedPS4);
            // The hash code for two instances of the same permission might be different, hence a hash code should not be used to 
            // compare two named permission sets.
            Console.WriteLine("The hash code of the original permission set is " + namedPS2.GetHashCode());
            Console.WriteLine("The hash code of the copy is " + namedPS4.GetHashCode());

        }
        catch (Exception e)
        {
            Console.WriteLine("Exception thrown: " + e.Message.ToString());
        }
    }

    public static bool DisplayPermissions(NamedPermissionSet namedPS1)
    {
        // Display results of namedPS.GetEnumerator.
        IEnumerator psEnumerator = namedPS1.GetEnumerator();

        while (psEnumerator.MoveNext())
        {
            Console.WriteLine(psEnumerator.Current);
        }

        return true;
    }
    // The following method uses the LocalIntranet permission set to create
    // a custom permission set named MyCompany.  The new permission set is
    // added to local Machine policy.  The custom named permission set is returned.
    private static NamedPermissionSet CreateCompanyPermission()
    {
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

        // Move through the policy levels to the Machine policy level.
        while (policyEnumerator.MoveNext())
        {
            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;

            if (currentLevel.Label == "Machine")
            {
                // Enumerate the permission sets in the Machine policy level.
                IList namedPermissions = currentLevel.NamedPermissionSets;
                IEnumerator namedPermission = namedPermissions.GetEnumerator();

                // Locate the LocalIntranet permission set.
                while (namedPermission.MoveNext())
                {
                    if (((NamedPermissionSet)namedPermission.Current).Name == "LocalIntranet")
                    {
                        // The current permission set is a copy of the LocalIntranet permission set.
                        // It can be modified to provide the permissions for the new permission set.
                        // Rename the copy to the name chosen for the new permission set.
                        ((NamedPermissionSet)namedPermission.Current).Name = "MyCompany";
                        ((NamedPermissionSet)namedPermission.Current).Description = "My custom named permission set";
                        IEnumerator permissions = ((NamedPermissionSet)namedPermission.Current).GetEnumerator();

                        // Remove the current security permission from the permission set and replace it 
                        // with a new security permission that does not have the right to assert permissions.
                        while (permissions.MoveNext())
                        {
                            if (permissions.Current.GetType().ToString() == "System.Security.Permissions.SecurityPermission")
                            {
                                // Remove the current security permission.
                                ((NamedPermissionSet)namedPermission.Current).RemovePermission(permissions.Current.GetType());

                                // Add a new security permission that only allows execution.
                                ((NamedPermissionSet)namedPermission.Current).AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                                break;
                            }
                        }

                        try
                        {
                            // If you run this application twice, the following instruction throws
                            // an exception because the named permission set already exists.
                            // You can remove the custom named permission set using either Caspole.exe or the  
                            // .NET Framework Configuration tool (Mscorcfg.msc).
                            currentLevel.AddNamedPermissionSet(((NamedPermissionSet)namedPermission.Current));
                            SecurityManager.SavePolicy();
                            return (NamedPermissionSet)namedPermission.Current;
                        }
                        // Catch the exception for a duplicate permission set.
                        catch (System.ArgumentException e)
                        {
                            Console.WriteLine(e.Message + "\n");
                            return (NamedPermissionSet)namedPermission.Current;
                        }
                    }
                }
            }
        }
        // The following code is executed only if the LocalIntranet permission set has been removed.
        return new NamedPermissionSet("Nothing");
    }

    // Test harness.
    static void Main(string[] args)
    {
        PermissionSetDemo();
        Console.WriteLine("Press any key to exit.");
        Console.Read();
    }
}


System.Object
  System.Security.PermissionSet
    System.Security.NamedPermissionSet

Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0
Mostrar: