FileCodeGroup 类

定义

注意

Code Access Security is not supported or honored by the runtime.

向符合成员条件的代码程序集授予权限以操作位于代码程序集中的文件。 此类不能被继承。

public ref class FileCodeGroup sealed : System::Security::Policy::CodeGroup
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public sealed class FileCodeGroup : System.Security.Policy.CodeGroup
[System.Serializable]
public sealed class FileCodeGroup : System.Security.Policy.CodeGroup
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class FileCodeGroup : System.Security.Policy.CodeGroup
public sealed class FileCodeGroup : System.Security.Policy.CodeGroup
[<System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type FileCodeGroup = class
    inherit CodeGroup
[<System.Serializable>]
type FileCodeGroup = class
    inherit CodeGroup
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type FileCodeGroup = class
    inherit CodeGroup
type FileCodeGroup = class
    inherit CodeGroup
Public NotInheritable Class FileCodeGroup
Inherits CodeGroup
继承
FileCodeGroup
属性

示例

以下示例演示如何使用 类的成员 FileCodeGroup

using namespace System;
using namespace System::Security;
using namespace System::Security::Policy;
using namespace System::Security::Permissions;
using namespace System::Reflection;

ref class Members
{
public:
   [STAThread]
   static void Main()
   {
      FileCodeGroup^ fileCodeGroup = constructDefaultGroup();
      
      // Create a deep copy of the FileCodeGroup.
      FileCodeGroup^ copyCodeGroup =
         dynamic_cast<FileCodeGroup^>(fileCodeGroup->Copy());

      CompareTwoCodeGroups( fileCodeGroup, copyCodeGroup );
      addPolicy(  &fileCodeGroup );
      addXmlMember(  &fileCodeGroup );
      updateMembershipCondition(  &fileCodeGroup );
      addChildCodeGroup(  &fileCodeGroup );
      Console::Write( L"Comparing the resolved code group " );
      Console::WriteLine( L"with the initial code group." );
      FileCodeGroup^ resolvedCodeGroup =
         ResolveGroupToEvidence( fileCodeGroup );
      if ( CompareTwoCodeGroups( fileCodeGroup, resolvedCodeGroup ) )
      {
         PrintCodeGroup( resolvedCodeGroup );
      }
      else
      {
         PrintCodeGroup( fileCodeGroup );
      }

      Console::WriteLine( L"This sample completed successfully; press Enter to exit." );
      Console::ReadLine();
   }

private:
   // Construct a new FileCodeGroup with Read, Write, Append
   // and PathDiscovery access.
   static FileCodeGroup^ constructDefaultGroup()
   {
      // Construct a new file code group that has complete access to
      // files in the specified path.
      FileCodeGroup^ fileCodeGroup = gcnew FileCodeGroup(
         gcnew AllMembershipCondition,FileIOPermissionAccess::AllAccess );

      // Set the name of the file code group.
      fileCodeGroup->Name = L"TempCodeGroup";

      // Set the description of the file code group.
      fileCodeGroup->Description = L"Temp folder permissions group";

      // Retrieve the string representation of the  fileCodeGroup�s
      // attributes. FileCodeGroup does not use AttributeString, so the
      // value should be null.
      if ( fileCodeGroup->AttributeString != nullptr )
      {
         throw gcnew NullReferenceException(
            L"The AttributeString property should be null." );
      }

      return fileCodeGroup;
   }

   // Add file permission to restrict write access to all files on the
   // local machine.
   static void addPolicy( interior_ptr<FileCodeGroup^> fileCodeGroup )
   {
      // Set the PolicyStatement property to a policy with read access to
      // the root directory of drive C.
      FileIOPermission^ rootFilePermissions =
         gcnew FileIOPermission( PermissionState::None );
      rootFilePermissions->AllLocalFiles =
         FileIOPermissionAccess::Read;
      rootFilePermissions->SetPathList(
         FileIOPermissionAccess::Read, L"C:\\" );
      NamedPermissionSet^ namedPermissions =
         gcnew NamedPermissionSet( L"RootPermissions" );
      namedPermissions->AddPermission( rootFilePermissions );
      ( *fileCodeGroup )->PolicyStatement =
         gcnew PolicyStatement( namedPermissions );
   }

   // Set the membership condition of the specified FileCodeGroup
   // to the Intranet zone.
   static void updateMembershipCondition( interior_ptr<FileCodeGroup^> fileCodeGroup )
   {
      ZoneMembershipCondition^ zoneCondition =
         gcnew ZoneMembershipCondition( SecurityZone::Intranet );
      ( *fileCodeGroup )->MembershipCondition = zoneCondition;
   }

   // Add a child group with read-access file permission to the specified
   // code group.
   static void addChildCodeGroup( interior_ptr<FileCodeGroup^> fileCodeGroup )
   {
      // Create a file code group with read-access permission.
      FileCodeGroup^ tempFolderCodeGroup = gcnew FileCodeGroup(
         gcnew AllMembershipCondition,FileIOPermissionAccess::Read );
      
      // Set the name of the child code group and add it to
      // the specified code group.
      tempFolderCodeGroup->Name = L"Read-only group";
      ( *fileCodeGroup )->AddChild( tempFolderCodeGroup );
   }

   // Compare the two specified file code groups for equality.
   static bool CompareTwoCodeGroups( FileCodeGroup^ firstCodeGroup,
      FileCodeGroup^ secondCodeGroup )
   {
      if ( firstCodeGroup->Equals( secondCodeGroup ) )
      {
         Console::WriteLine( L"The two code groups are equal." );
         return true;
      }
      else
      {
         Console::WriteLine( L"The two code groups are not equal." );
         return false;
      }
   }

   // Retrieve the resolved policy based on Evidence from the executing
   // assembly found in the specified code group.
   static String^ ResolveEvidence( CodeGroup^ fileCodeGroup )
   {
      String^ policyString = L"";
      
      // Resolve the policy based on evidence in the executing assembly.
      Assembly^ assembly = Members::typeid->Assembly;
      Evidence^ executingEvidence = assembly->Evidence;
      PolicyStatement^ policy = fileCodeGroup->Resolve( executingEvidence );

      if ( policy != nullptr )
      {
         policyString = policy->ToString();
      }

      return policyString;
   }

   // Retrieve the resolved code group based on the Evidence from
   // the executing assembly found in the specified code group.
   static FileCodeGroup^ ResolveGroupToEvidence( FileCodeGroup^ fileCodeGroup )
   {
      // Resolve matching code groups to the executing assembly.
      Assembly^ assembly = Members::typeid->Assembly;
      Evidence^ evidence = assembly->Evidence;
      CodeGroup^ codeGroup = fileCodeGroup->ResolveMatchingCodeGroups( evidence );

      return dynamic_cast<FileCodeGroup^>(codeGroup);
   }

   // If a domain attribute is not found in the specified FileCodeGroup,
   // add a child XML element identifying a custom membership condition.
   static void addXmlMember( interior_ptr<FileCodeGroup^> fileCodeGroup )
   {
      SecurityElement^ xmlElement = ( *fileCodeGroup )->ToXml();

      SecurityElement^ rootElement = gcnew SecurityElement( L"CodeGroup" );
      if ( xmlElement->Attribute(L"domain") == nullptr )
      {
         SecurityElement^ newElement = gcnew SecurityElement(
            L"CustomMembershipCondition" );
         newElement->AddAttribute( L"class", L"CustomMembershipCondition" );
         newElement->AddAttribute( L"version", L"1" );
         newElement->AddAttribute( L"domain", L"contoso.com" );
         rootElement->AddChild( newElement );
         ( *fileCodeGroup )->FromXml( rootElement );
      }

      Console::WriteLine( L"Added a custom membership condition:" );
      Console::WriteLine( rootElement );
   }

   // Print the properties of the specified code group to the console.
   static void PrintCodeGroup( CodeGroup^ codeGroup )
   {
      // Compare the type of the specified object with the FileCodeGroup
      // type.
      if (  !codeGroup->GetType()->Equals( FileCodeGroup::typeid ) )
      {
         throw gcnew ArgumentException( L"Expected the FileCodeGroup type." );
      }

      String^ codeGroupName = codeGroup->Name;
      String^ membershipCondition = codeGroup->MembershipCondition->ToString();
      
      String^ permissionSetName = codeGroup->PermissionSetName;

      int hashCode = codeGroup->GetHashCode();

      String^ mergeLogic = L"";
      
      if ( codeGroup->MergeLogic->Equals( L"Union" ) )
      {
         mergeLogic = L" with Union merge logic";
      }
      
      // Retrieve the class path for FileCodeGroup.
      String^ fileGroupClass = codeGroup->ToString();
      
      // Write summary to the console window.
      Console::WriteLine( L"\n*** {0} summary ***", fileGroupClass );
      Console::Write( L"A FileCodeGroup named " );
      Console::Write( L"{0}{1}", codeGroupName, mergeLogic );
      Console::Write( L" has been created with hash code{0}.", hashCode );
      Console::Write( L"This code group contains a {0}", membershipCondition );
      Console::Write( L" membership condition with the " );
      Console::Write( L"{0} permission set. ", permissionSetName );
      Console::Write( L"The code group has the following security policy: " );
      Console::WriteLine( ResolveEvidence( codeGroup ) );
      int childCount = codeGroup->Children->Count;
      if ( childCount > 0 )
      {
         Console::Write( L"There are {0}", childCount );
         Console::WriteLine( L" child code groups in this code group." );
         
         // Iterate through the child code groups to display their names
         // and remove them from the specified code group.
         for ( int i = 0; i < childCount; i++ )
         {
            // Get child code group as type FileCodeGroup.
            FileCodeGroup^ childCodeGroup =
               dynamic_cast<FileCodeGroup^>(codeGroup->Children->default[ i ]);
            
            Console::Write( L"Removing the {0}.", childCodeGroup->Name );
            // Remove child code group.

            codeGroup->RemoveChild( childCodeGroup );
         }
         Console::WriteLine();
      }
      else
      {
         Console::Write( L"There are no child code groups" );
         Console::WriteLine( L" in this code group." );
      }
   }
};

int main()
{
   Members::Main();
}

//
// This sample produces the following output:
//
// The two code groups are equal.
// Added a custom membership condition:
// <CustomMembershipCondition class="CustomMembershipCondition"
//                                version="1"
//                                domain="contoso.com"/>
// Comparing the resolved code group with the initial code group.
// The two code groups are not equal.
//
// *** System.Security.Policy.FileCodeGroup summary ***
// A FileCodeGroup named  with Union merge logic has been created with hash
// code 113151473. This code group contains a Zone - Intranet membership
// condition with the Same directory FileIO - NoAccess permission set. The
// code group has the following security policy:
// There are 1 child code groups in this code group.
// Removing the Read-only group.
// This sample completed successfully; press Enter to exit.
using System;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;

class Members
{
    [STAThread]
    static void Main(string[] args)
    {
        FileCodeGroup fileCodeGroup = constructDefaultGroup();
        
        // Create a deep copy of the FileCodeGroup.
        FileCodeGroup copyCodeGroup = (FileCodeGroup)fileCodeGroup.Copy();

        CompareTwoCodeGroups(fileCodeGroup, copyCodeGroup);

        addPolicy(ref fileCodeGroup);
        addXmlMember(ref fileCodeGroup);
        updateMembershipCondition(ref fileCodeGroup);
        addChildCodeGroup(ref fileCodeGroup);

        Console.Write("Comparing the resolved code group ");
        Console.WriteLine("with the initial code group.");
        FileCodeGroup resolvedCodeGroup =
            ResolveGroupToEvidence(fileCodeGroup);
        if (CompareTwoCodeGroups(fileCodeGroup, resolvedCodeGroup))
        {
            PrintCodeGroup(resolvedCodeGroup);
        }
        else
        {
            PrintCodeGroup(fileCodeGroup);
        }
        
        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");
        Console.ReadLine();
    }

    // Construct a new FileCodeGroup with Read, Write, Append 
    // and PathDiscovery access.
    private static FileCodeGroup constructDefaultGroup()
    {
        // Construct a new file code group that has complete access to
        // files in the specified path.
        FileCodeGroup fileCodeGroup = 
            new FileCodeGroup(
            new AllMembershipCondition(),
            FileIOPermissionAccess.AllAccess);

        // Set the name of the file code group.
        fileCodeGroup.Name = "TempCodeGroup";

        // Set the description of the file code group.
        fileCodeGroup.Description = "Temp folder permissions group";

        // Retrieve the string representation of the  fileCodeGroup’s 
        // attributes. FileCodeGroup does not use AttributeString, so the
        // value should be null.
        if (fileCodeGroup.AttributeString != null)
        {
            throw new NullReferenceException(
                "The AttributeString property should be null.");
        }

        return fileCodeGroup;
    }

    // Add file permission to restrict write access to all files on the
    // local machine.
    private static void addPolicy(ref FileCodeGroup fileCodeGroup)
    {
        // Set the PolicyStatement property to a policy with read access to
        // the root directory of drive C.
        FileIOPermission rootFilePermissions = 
            new FileIOPermission(PermissionState.None);
        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read,"C:\\");

        NamedPermissionSet namedPermissions =
            new NamedPermissionSet("RootPermissions");
        namedPermissions.AddPermission(rootFilePermissions);
        
        fileCodeGroup.PolicyStatement =
            new PolicyStatement(namedPermissions);
    }

    // Set the membership condition of the specified FileCodeGroup 
    // to the Intranet zone.
    private static void updateMembershipCondition(
        ref FileCodeGroup fileCodeGroup)
    {
        ZoneMembershipCondition zoneCondition =
            new ZoneMembershipCondition(SecurityZone.Intranet);
        fileCodeGroup.MembershipCondition = zoneCondition;
    }

    // Add a child group with read-access file permission to the specified 
    // code group.
    private static void addChildCodeGroup(ref FileCodeGroup fileCodeGroup)
    {
        // Create a file code group with read-access permission.
        FileCodeGroup tempFolderCodeGroup = new FileCodeGroup(
            new AllMembershipCondition(), 
            FileIOPermissionAccess.Read);

        // Set the name of the child code group and add it to 
        // the specified code group.
        tempFolderCodeGroup.Name = "Read-only group";
        fileCodeGroup.AddChild(tempFolderCodeGroup);
    }

    // Compare the two specified file code groups for equality.
    private static bool CompareTwoCodeGroups(
        FileCodeGroup firstCodeGroup, FileCodeGroup secondCodeGroup)
    {
        if (firstCodeGroup.Equals(secondCodeGroup))
        {
            Console.WriteLine("The two code groups are equal.");
            return true;
        }
        else 
        {
            Console.WriteLine("The two code groups are not equal.");
            return false;
        }
    }

    // Retrieve the resolved policy based on Evidence from the executing 
    // assembly found in the specified code group.
    private static string ResolveEvidence(CodeGroup fileCodeGroup)
    {
        string policyString = "";

        // Resolve the policy based on evidence in the executing assembly.
        Assembly assembly = typeof(Members).Assembly;
        Evidence executingEvidence = assembly.Evidence;

        PolicyStatement policy = fileCodeGroup.Resolve(executingEvidence);

        if (policy != null)
        {
            policyString = policy.ToString();
        }

        return policyString;
    }

    // Retrieve the resolved code group based on the Evidence from 
    // the executing assembly found in the specified code group.
    private static FileCodeGroup ResolveGroupToEvidence(
        FileCodeGroup fileCodeGroup)
    {
        // Resolve matching code groups to the executing assembly.
        Assembly assembly = typeof(Members).Assembly;
        Evidence evidence = assembly.Evidence;
        CodeGroup codeGroup = 
            fileCodeGroup.ResolveMatchingCodeGroups(evidence);

        return (FileCodeGroup)codeGroup;
    }

    // If a domain attribute is not found in the specified FileCodeGroup,
    // add a child XML element identifying a custom membership condition.
    private static void addXmlMember(ref FileCodeGroup fileCodeGroup)
    {
        SecurityElement xmlElement = fileCodeGroup.ToXml();

        SecurityElement rootElement = new SecurityElement("CodeGroup");

        if (xmlElement.Attribute("domain") == null) 
        {
            SecurityElement newElement = 
                new SecurityElement("CustomMembershipCondition");
            newElement.AddAttribute("class","CustomMembershipCondition");
            newElement.AddAttribute("version","1");
            newElement.AddAttribute("domain","contoso.com");

            rootElement.AddChild(newElement);

            fileCodeGroup.FromXml(rootElement);
        }

        Console.WriteLine("Added a custom membership condition:");
        Console.WriteLine(rootElement.ToString());
    }

    // Print the properties of the specified code group to the console.
    private static void PrintCodeGroup(CodeGroup codeGroup)
    {
        // Compare the type of the specified object with the FileCodeGroup
        // type.
        if (!codeGroup.GetType().Equals(typeof(FileCodeGroup)))
        {
            throw new ArgumentException("Expected the FileCodeGroup type.");
        }
        
        string codeGroupName = codeGroup.Name;
        string membershipCondition = codeGroup.MembershipCondition.ToString();
        string permissionSetName = codeGroup.PermissionSetName;

        int hashCode = codeGroup.GetHashCode();

        string mergeLogic = "";
        if (codeGroup.MergeLogic.Equals("Union"))
        {
            mergeLogic = " with Union merge logic";
        }

        // Retrieve the class path for FileCodeGroup.
        string fileGroupClass = codeGroup.ToString();

        // Write summary to the console window.
        Console.WriteLine("\n*** " + fileGroupClass + " summary ***");
        Console.Write("A FileCodeGroup named ");
        Console.Write(codeGroupName + mergeLogic);
        Console.Write(" has been created with hash code" + hashCode + ".");
        Console.Write("This code group contains a " + membershipCondition);
        Console.Write(" membership condition with the ");
        Console.Write(permissionSetName + " permission set. ");

        Console.Write("The code group has the following security policy: ");
        Console.WriteLine(ResolveEvidence(codeGroup));

        int childCount = codeGroup.Children.Count;
        if (childCount > 0 )
        {
            Console.Write("There are " + childCount);
            Console.WriteLine(" child code groups in this code group.");

            // Iterate through the child code groups to display their names
            // and remove them from the specified code group.
            for (int i=0; i < childCount; i++)
            {
                // Get child code group as type FileCodeGroup.
                FileCodeGroup childCodeGroup = 
                    (FileCodeGroup)codeGroup.Children[i];
                
                Console.Write("Removing the " + childCodeGroup.Name + ".");
                // Remove child code group.
                codeGroup.RemoveChild(childCodeGroup);
            }

            Console.WriteLine();
        }
        else
        {
            Console.Write("There are no child code groups");
            Console.WriteLine(" in this code group.");
        }
    }
}
//
// This sample produces the following output:
//
// The two code groups are equal.
// Added a custom membership condition:
// <CustomMembershipCondition class="CustomMembershipCondition"
//                                version="1"
//                                domain="contoso.com"/>
// Comparing the resolved code group with the initial code group.
// The two code groups are not equal.
// 
// *** System.Security.Policy.FileCodeGroup summary ***
// A FileCodeGroup named  with Union merge logic has been created with hash
// code 113151473. This code group contains a Zone - Intranet membership
// condition with the Same directory FileIO - NoAccess permission set. The
// code group has the following security policy:
// There are 1 child code groups in this code group.
// Removing the Read-only group.
// This sample completed successfully; press Enter to exit.
Imports System.Security
Imports System.Security.Policy
Imports System.Security.Permissions
Imports System.Reflection
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    ' Event handler for Run button.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        tbxOutput.Cursor = Cursors.WaitCursor
        tbxOutput.Text = ""

        Dim fileCodeGroup As FileCodeGroup = constructDefaultGroup()

        ' Create a deep copy of the FileCodeGroup;
        Dim copyCodeGroup As FileCodeGroup = _
            CType(fileCodeGroup.Copy(), FileCodeGroup)

        CompareTwoCodeGroups(fileCodeGroup, copyCodeGroup)

        addPolicy(fileCodeGroup)
        addXmlMember(fileCodeGroup)
        updateMembershipCondition(fileCodeGroup)
        addChildCodeGroup(fileCodeGroup)

        WriteLine("Comparing the resolved code group with the initial " + _
            "code group:")
        Dim resolvedCodeGroup As FileCodeGroup
        resolvedCodeGroup = ResolveGroupToEvidence(fileCodeGroup)

        If (CompareTwoCodeGroups(fileCodeGroup, resolvedCodeGroup)) Then
            PrintCodeGroup(resolvedCodeGroup)
        Else
            PrintCodeGroup(fileCodeGroup)
        End If

        ' Reset the cursor and conclude application.
        tbxOutput.AppendText(vbCrLf + "This sample completed " + _
            "successfully; press Exit to continue.")
        tbxOutput.Cursor = Cursors.Default
    End Sub
    ' Construct a new FileCodeGroup with read, write, append and 
    ' discovery access.
    Private Function constructDefaultGroup() As FileCodeGroup
        ' Construct a file code group with read, write, append and 
        ' discovery access.
        Dim fileCodeGroup As New FileCodeGroup( _
            New AllMembershipCondition, _
            FileIOPermissionAccess.AllAccess)

        ' Set the name of the file code group.
        fileCodeGroup.Name = "TempCodeGroup"

        ' Set the description of the file code group.
        fileCodeGroup.Description = "Temp folder permissions group"

        ' Retrieve the string representation of the Policy's attributes.
        ' FileCodeGroup does not use AttributeString, so the value should
        ' be null.
        If (Not fileCodeGroup.AttributeString Is Nothing) Then
            Throw New NullReferenceException( _
                "AttributeString property is not empty")
        End If

        Return fileCodeGroup
    End Function

    ' Add file permission to restrict write access to all files on the 
    ' local machine.
    Private Sub addPolicy(ByRef fileCodeGroup As FileCodeGroup)
        ' Set the PolicyStatement property to a policy with
        ' read access to c:\.
        Dim rootFilePermissions As New FileIOPermission(PermissionState.None)
        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\")

        Dim namedPermissions As New NamedPermissionSet("RootPermissions")
        namedPermissions.AddPermission(rootFilePermissions)

        fileCodeGroup.PolicyStatement = New PolicyStatement(namedPermissions)
    End Sub

    ' Set the membership condition of the specified FileCodeGroup to 
    ' Intranet zone.
    Private Sub updateMembershipCondition( _
        ByRef fileCodeGroup As FileCodeGroup)

        ' Set the membership condition to the Intranet zone.
        Dim zoneCondition As _
            New ZoneMembershipCondition(SecurityZone.Intranet)

        fileCodeGroup.MembershipCondition = zoneCondition
    End Sub

    ' Add a child group with read-access file permissions to the specified
    ' code group.
    Private Sub addChildCodeGroup(ByRef fileCodeGroup As FileCodeGroup)
        ' Create a file code group with read access.
        Dim tempFolderCodeGroup As New FileCodeGroup( _
            New AllMembershipCondition, _
            FileIOPermissionAccess.Read)

        ' Set the name of the child code group and add it to the specified 
        ' code group.
        tempFolderCodeGroup.Name = "Read-only group"
        fileCodeGroup.AddChild(tempFolderCodeGroup)
    End Sub

    ' Compare two specified FileCodeGroups for equality.
    Private Function CompareTwoCodeGroups( _
        ByVal firstCodeGroup As FileCodeGroup, _
        ByVal secondCodeGroup As FileCodeGroup) As Boolean

        ' Compare two FileCodeGroups for equality.
        If (firstCodeGroup.Equals(secondCodeGroup)) Then
            WriteLine("The two code groups are equal.")
            Return True
        Else
            WriteLine("The two code groups are not equal.")
            Return False
        End If

    End Function

    ' Retrieve the resolved policy based on the executing evidence found 
    ' in the specified code group.
    Private Function ResolveEvidence( _
        ByVal fileCodeGroup As CodeGroup) As String

        Dim policyString As String = ""

        ' Resolve the policy based on the executing assemlby's evidence.
        Dim executingAssembly As [Assembly]
        executingAssembly = Me.GetType().Assembly

        Dim executingEvidence As Evidence = executingAssembly.Evidence

        Dim policy As PolicyStatement
        policy = fileCodeGroup.Resolve(executingEvidence)

        If (Not policy Is Nothing) Then
            policyString = policy.ToString()
        End If

        Return policyString
    End Function

    ' Retrieve the resolved code group based on the executing evidence found
    ' in the specified code group.
    Private Function ResolveGroupToEvidence( _
        ByVal fileCodeGroup As FileCodeGroup) As FileCodeGroup

        ' Resolve matching code groups to the executing assembly.
        Dim executingAssembly As [Assembly]
        executingAssembly = Me.GetType().Assembly

        Dim evidence As Evidence = executingAssembly.Evidence

        Dim codeGroup As CodeGroup
        codeGroup = fileCodeGroup.ResolveMatchingCodeGroups(evidence)

        Return CType(codeGroup, FileCodeGroup)
    End Function

    ' If domain attribute is not found in specified FileCodeGroup, 
    ' add a child Xml element identifying a custom membership condition.
    Private Sub addXmlMember(ByRef fileCodeGroup As FileCodeGroup)
        Dim xmlElement As SecurityElement = fileCodeGroup.ToXml()

        Dim rootElement As New SecurityElement("CodeGroup")
        If (xmlElement.Attribute("domain") Is Nothing) Then
            Dim newElement As New SecurityElement("CustomMembershipCondition")
            newElement.AddAttribute("class", "CustomMembershipCondition")
            newElement.AddAttribute("version", "1")
            newElement.AddAttribute("domain", "contoso.com")

            rootElement.AddChild(newElement)

            fileCodeGroup.FromXml(rootElement)

        End If

        WriteLine("Added a custom membership condition:")
        WriteLine(rootElement.ToString())
    End Sub

    ' Print the properties of the specified code group to the output textbox.
    Private Sub PrintCodeGroup(ByVal codeGroup As CodeGroup)
        ' Compare specified object's type with the FileCodeGroup type.
        If (Not codeGroup.GetType() Is GetType(FileCodeGroup)) Then
            Throw New ArgumentException("Excepted FileCodeGroup type")
        End If

        Dim codeGroupName As String = codeGroup.Name
        Dim membershipCondition As String
        membershipCondition = codeGroup.MembershipCondition.ToString()

        Dim permissionSetName As String = codeGroup.PermissionSetName

        Dim hashCode As Integer = codeGroup.GetHashCode()

        Dim mergeLogic As String = ""
        If (codeGroup.MergeLogic.Equals("Union")) Then
            mergeLogic = " with Union merge logic"
        End If

        ' Retrieve the class path for FileCodeGroup.
        Dim fileGroupClass As String = codeGroup.ToString()

        ' Write summary to console window.
        WriteLine(vbCrLf + "*** " + fileGroupClass + " summary ***")
        Write("A FileCodeGroup named " + codeGroupName + mergeLogic)
        Write(" has been created with hash code(" + hashCode.ToString())
        Write("). It contains a " + membershipCondition)
        Write(" membership condition with the ")
        Write(permissionSetName + " permission set. ")

        WriteLine("It has the following policy: " + _
            ResolveEvidence(codeGroup))
        Dim childCount As Integer = codeGroup.Children.Count
        If (childCount > 0) Then
            Write("There are " + childCount.ToString())
            WriteLine(" child elements in the code group:")

            ' Iterate through the child code groups to display their names and
            '  remove them from the specified code group.
            For i As Int16 = 0 To childCount - 1 Step 1
                ' Get child code group as type FileCodeGroup.
                Dim childCodeGroup As FileCodeGroup
                childCodeGroup = CType(codeGroup.Children(i), FileCodeGroup)

                Write("Removing the " + childCodeGroup.Name + ".")
                ' Remove child codegroup.
                codeGroup.RemoveChild(childCodeGroup)
            Next

            WriteLine("")

        Else
            WriteLine("There are no children found in the code group:")

        End If
    End Sub
    ' Write message to the output textbox.
    Private Sub Write(ByVal message As String)
        tbxOutput.AppendText(message)

    End Sub
    ' Write message with carriage return to the output textbox.
    Private Sub WriteLine(ByVal message As String)
        tbxOutput.AppendText(message + vbCrLf)

    End Sub


    ' Event handler for Exit button.
    Private Sub Button2_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click

        Application.Exit()
    End Sub
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents tbxOutput As System.Windows.Forms.RichTextBox
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.tbxOutput = New System.Windows.Forms.RichTextBox
        Me.Panel2.SuspendLayout()
        Me.Panel1.SuspendLayout()
        Me.SuspendLayout()
        '
        'Panel2
        '
        Me.Panel2.Controls.Add(Me.Button1)
        Me.Panel2.Controls.Add(Me.Button2)
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Panel2.DockPadding.All = 20
        Me.Panel2.Location = New System.Drawing.Point(0, 320)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(616, 64)
        Me.Panel2.TabIndex = 1
        '
        'Button1
        '
        Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button1.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button1.Location = New System.Drawing.Point(446, 20)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75, 24)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "&Run"
        '
        'Button2
        '
        Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button2.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button2.Location = New System.Drawing.Point(521, 20)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(75, 24)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "E&xit"
        '
        'Panel1
        '
        Me.Panel1.Controls.Add(Me.tbxOutput)
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel1.DockPadding.All = 20
        Me.Panel1.Location = New System.Drawing.Point(0, 0)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(616, 320)
        Me.Panel1.TabIndex = 2
        '
        'tbxOutput
        '
        Me.tbxOutput.AccessibleDescription = _
            "Displays output from application."
        Me.tbxOutput.AccessibleName = "Output textbox."
        Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
        Me.tbxOutput.Location = New System.Drawing.Point(20, 20)
        Me.tbxOutput.Name = "tbxOutput"
        Me.tbxOutput.Size = New System.Drawing.Size(576, 280)
        Me.tbxOutput.TabIndex = 1
        Me.tbxOutput.Text = "Click the Run button to run the application."
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
        Me.ClientSize = New System.Drawing.Size(616, 384)
        Me.Controls.Add(Me.Panel1)
        Me.Controls.Add(Me.Panel2)
        Me.Name = "Form1"
        Me.Text = "FileCodeGroup"
        Me.Panel2.ResumeLayout(False)
        Me.Panel1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region
End Class
'
' This sample produces the following output:
'
' The two code groups are equal.
' Added a custom membership condition:
'    <CustomMembershipCondition class="CustomMembershipCondition"
'                               version="1"
'                               domain="contoso.com"/>
' 
' Comparing the resolved code group with the initial code group:
' The two code groups are not equal.
' 
' *** System.Security.Policy.FileCodeGroup summary ***
' A FileCodeGroup named  with Union merge logic has been created with hash
' code (113152269). It contains a Zone - Intranet membership condition with
' the Same directory FileIO - NoAccess permission set. Has the following
' policy: 
' There are 1 child elements in the code group:
' Removing the Read-only group.
' 
' This sample completed successfully; press Exit to continue.

注解

注意

代码访问安全性 (CAS) 已在所有版本的 .NET Framework 和 .NET 中弃用。 如果使用与 CAS 相关的 API,最新版本的 .NET 不会遵循 CAS 注释,并会生成错误。 开发人员应寻求用于完成安全任务的替代方法。

代码组是代码访问安全策略的构建基块。 每个策略级别都包含一个可以具有子代码组的根代码组。 每个子代码组可以有自己的子代码组;此行为扩展到任意数量的级别,形成一个树。 每个代码组都有一个成员资格条件,该条件根据该程序集的证据确定给定程序集是否属于该程序集。 只有其成员身份条件与给定程序集及其子代码组匹配的代码组才应用策略。

FileCodeGroup 具有与 相同的子匹配语义 UnionCodeGroup。 但是, FileCodeGroup 返回包含动态计算 FileIOPermission 的权限集,该权限集授予文件对运行代码的目录的访问权限; UnionCodeGroup 仅返回静态权限集。 授予的文件访问权限的类型作为参数传递给构造函数。

此代码组仅匹配通过文件协议运行的程序集,即具有指向文件或 UNC 路径的 URL 的程序集。

构造函数

FileCodeGroup(IMembershipCondition, FileIOPermissionAccess)
已过时.

初始化 FileCodeGroup 类的新实例。

属性

AttributeString
已过时.

获取代码组策略声明的特性的字符串表示形式。

Children
已过时.

获取或设置代码组的子代码组的排序列表。

(继承自 CodeGroup)
Description
已过时.

获取或设置代码组的说明。

(继承自 CodeGroup)
MembershipCondition
已过时.

获取或设置代码组的成员条件。

(继承自 CodeGroup)
MergeLogic
已过时.

获取合并逻辑。

Name
已过时.

获取或设置代码组的名称。

(继承自 CodeGroup)
PermissionSetName
已过时.

获取代码组的命名的权限集的名称。

PolicyStatement
已过时.

获取或设置与该代码组关联的策略声明。

(继承自 CodeGroup)

方法

AddChild(CodeGroup)
已过时.

将子代码组添加到当前代码组。

(继承自 CodeGroup)
Copy()
已过时.

生成当前代码组的深层副本。

CreateXml(SecurityElement, PolicyLevel)
已过时.

当在派生类中被重写时,序列化导出的代码组所特有的属性和内部状态,并将序列化添加到指定的 SecurityElement

(继承自 CodeGroup)
Equals(CodeGroup, Boolean)
已过时.

确定指定的代码组是否等效于当前代码组,如果指定,还检查子代码组。

(继承自 CodeGroup)
Equals(Object)
已过时.

确定指定的代码组是否等效于当前代码组。

FromXml(SecurityElement)
已过时.

从 XML 编码重新构造具有给定状态的安全对象。

(继承自 CodeGroup)
FromXml(SecurityElement, PolicyLevel)
已过时.

从 XML 编码重新构造具有给定的状态和策略级别的安全对象。

(继承自 CodeGroup)
GetHashCode()
已过时.

获取当前代码组的哈希代码。

GetType()
已过时.

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()
已过时.

创建当前 Object 的浅表副本。

(继承自 Object)
ParseXml(SecurityElement, PolicyLevel)
已过时.

当在派生类中被重写时,从指定的 SecurityElement 重新构造导出的代码组所特有的属性和内部状态。

(继承自 CodeGroup)
RemoveChild(CodeGroup)
已过时.

移除指定的子代码组。

(继承自 CodeGroup)
Resolve(Evidence)
已过时.

对一组证据解析代码组及其子代的策略。

ResolveMatchingCodeGroups(Evidence)
已过时.

解析匹配的代码组。

ToString()
已过时.

返回表示当前对象的字符串。

(继承自 Object)
ToXml()
已过时.

创建安全对象及其当前状态的 XML 编码。

(继承自 CodeGroup)
ToXml(PolicyLevel)
已过时.

创建安全对象、其当前状态以及代码所在策略级别的 XML 编码。

(继承自 CodeGroup)

适用于