X509Certificate2Collection Classe

Definição

Representa uma coleção de objetos X509Certificate2 .Represents a collection of X509Certificate2 objects. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class X509Certificate2Collection : System::Security::Cryptography::X509Certificates::X509CertificateCollection
public class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection
type X509Certificate2Collection = class
    inherit X509CertificateCollection
Public Class X509Certificate2Collection
Inherits X509CertificateCollection
Herança
X509Certificate2Collection
Herança
X509Certificate2Collection

Exemplos

O exemplo de código a seguir abre o repositório de certificados pessoais do usuário atual, seleciona somente certificados válidos, permite que o usuário selecione um certificado e, em seguida, grave informações de certificado e cadeia de certificados no console do.The following code example opens the current user's personal certificate store, selects only valid certificates, allows the user to select a certificate, and then writes certificate and certificate chain information to the console. A saída depende do certificado que o usuário seleciona.The output depends on the certificate the user selects.

#using <System.dll>
#using <System.Security.dll>

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Permissions;
using namespace System::IO;
using namespace System::Security::Cryptography::X509Certificates;
int main()
{
   try
   {
      X509Store ^ store = gcnew X509Store( "MY",StoreLocation::CurrentUser );
      store->Open( static_cast<OpenFlags>(OpenFlags::ReadOnly | OpenFlags::OpenExistingOnly) );
      X509Certificate2Collection ^ collection = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
      X509Certificate2Collection ^ fcollection = dynamic_cast<X509Certificate2Collection^>(collection->Find( X509FindType::FindByTimeValid, DateTime::Now, false ));
      X509Certificate2Collection ^ scollection = X509Certificate2UI::SelectFromCollection(fcollection, "Test Certificate Select","Select a certificate from the following list to get information on that certificate",X509SelectionFlag::MultiSelection);
      Console::WriteLine( "Number of certificates: {0}{1}", scollection->Count, Environment::NewLine );
      System::Collections::IEnumerator^ myEnum = scollection->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum->Current);
         array<Byte>^rawdata = x509->RawData;
         Console::WriteLine( "Content Type: {0}{1}", X509Certificate2::GetCertContentType( rawdata ), Environment::NewLine );
         Console::WriteLine( "Friendly Name: {0}{1}", x509->FriendlyName, Environment::NewLine );
         Console::WriteLine( "Certificate Verified?: {0}{1}", x509->Verify(), Environment::NewLine );
         Console::WriteLine( "Simple Name: {0}{1}", x509->GetNameInfo( X509NameType::SimpleName, true ), Environment::NewLine );
         Console::WriteLine( "Signature Algorithm: {0}{1}", x509->SignatureAlgorithm->FriendlyName, Environment::NewLine );
         Console::WriteLine( "Private Key: {0}{1}", x509->PrivateKey->ToXmlString( false ), Environment::NewLine );
         Console::WriteLine( "Public Key: {0}{1}", x509->PublicKey->Key->ToXmlString( false ), Environment::NewLine );
         Console::WriteLine( "Certificate Archived?: {0}{1}", x509->Archived, Environment::NewLine );
         Console::WriteLine( "Length of Raw Data: {0}{1}", x509->RawData->Length, Environment::NewLine );
         x509->Reset();
      }
      store->Close();
   }
   catch ( CryptographicException^ ) 
   {
      Console::WriteLine( "Information could not be written out for this certificate." );
   }

}

using System;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class CertSelect
{
    static void Main()
    {
        X509Store store = new X509Store("MY",StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid,DateTime.Now,false);
        X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select","Select a certificate from the following list to get information on that certificate",X509SelectionFlag.MultiSelection);
        Console.WriteLine("Number of certificates: {0}{1}",scollection.Count,Environment.NewLine);

        foreach (X509Certificate2 x509 in scollection)
        {
            try
            {
                byte[] rawdata = x509.RawData;
                Console.WriteLine("Content Type: {0}{1}",X509Certificate2.GetCertContentType(rawdata),Environment.NewLine);
                Console.WriteLine("Friendly Name: {0}{1}",x509.FriendlyName,Environment.NewLine);
                Console.WriteLine("Certificate Verified?: {0}{1}",x509.Verify(),Environment.NewLine);
                Console.WriteLine("Simple Name: {0}{1}",x509.GetNameInfo(X509NameType.SimpleName,true),Environment.NewLine);
                Console.WriteLine("Signature Algorithm: {0}{1}",x509.SignatureAlgorithm.FriendlyName,Environment.NewLine);
                Console.WriteLine("Public Key: {0}{1}",x509.PublicKey.Key.ToXmlString(false),Environment.NewLine);
                Console.WriteLine("Certificate Archived?: {0}{1}",x509.Archived,Environment.NewLine);
                Console.WriteLine("Length of Raw Data: {0}{1}",x509.RawData.Length,Environment.NewLine);
                X509Certificate2UI.DisplayCertificate(x509);
                x509.Reset();
            }
            catch (CryptographicException)
            {
                Console.WriteLine("Information could not be written out for this certificate.");
            }
        }
        store.Close();
    }
}
Imports System.Security.Cryptography
Imports System.Security.Permissions
Imports System.IO
Imports System.Security.Cryptography.X509Certificates

Class CertSelect

    Shared Sub Main()

        Dim store As New X509Store("MY", StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly)

        Dim collection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Dim fcollection As X509Certificate2Collection = CType(collection.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection)
        Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.MultiSelection)
        Console.WriteLine("Number of certificates: {0}{1}", scollection.Count, Environment.NewLine)
         
        For Each x509 As X509Certificate2 In scollection
            Try
                Dim rawdata As Byte() = x509.RawData
                Console.WriteLine("Content Type: {0}{1}", X509Certificate2.GetCertContentType(rawdata), Environment.NewLine)
                Console.WriteLine("Friendly Name: {0}{1}", x509.FriendlyName, Environment.NewLine)
                Console.WriteLine("Certificate Verified?: {0}{1}", x509.Verify(), Environment.NewLine)
                Console.WriteLine("Simple Name: {0}{1}", x509.GetNameInfo(X509NameType.SimpleName, True), Environment.NewLine)
                Console.WriteLine("Signature Algorithm: {0}{1}", x509.SignatureAlgorithm.FriendlyName, Environment.NewLine)
                Console.WriteLine("Public Key: {0}{1}", x509.PublicKey.Key.ToXmlString(False), Environment.NewLine)
                Console.WriteLine("Certificate Archived?: {0}{1}", x509.Archived, Environment.NewLine)
                Console.WriteLine("Length of Raw Data: {0}{1}", x509.RawData.Length, Environment.NewLine)
                X509Certificate2UI.DisplayCertificate(x509)
                x509.Reset()         
             Catch cExcept As CryptographicException
                 Console.WriteLine("Information could not be written out for this certificate.")
             End Try
        Next x509

        store.Close()
    End Sub
End Class

Comentários

Quando um X509Certificate2 repositório é aberto, o resultado é representado por um X509Certificate2Collection objeto.When an X509Certificate2 store is opened, the result is represented by an X509Certificate2Collection object. Se você estiver familiarizado com as construções de API criptográfica não gerenciadas, poderá considerar um X509Certificate2Collection repositório de objetos do as X509Certificate2 .If you are familiar with the unmanaged Cryptographic API constructs, you can think of an X509Certificate2Collection as a memory store of X509Certificate2 objects.

Construtores

X509Certificate2Collection()

Inicializa uma nova instância da classe X509Certificate2Collection sem nenhuma informações de X509Certificate2.Initializes a new instance of the X509Certificate2Collection class without any X509Certificate2 information.

X509Certificate2Collection(X509Certificate2)

Inicializa uma nova instância da classe X509Certificate2Collection usando um objeto X509Certificate2.Initializes a new instance of the X509Certificate2Collection class using an X509Certificate2 object.

X509Certificate2Collection(X509Certificate2[])

Inicializa uma nova instância da classe X509Certificate2Collection usando uma matriz de objetos X509Certificate2.Initializes a new instance of the X509Certificate2Collection class using an array of X509Certificate2 objects.

X509Certificate2Collection(X509Certificate2Collection)

Inicializa uma nova instância da classe X509Certificate2Collection usando a coleção de certificado especificada.Initializes a new instance of the X509Certificate2Collection class using the specified certificate collection.

Propriedades

Capacity

Obtém ou define o número de elementos que o CollectionBase pode conter.Gets or sets the number of elements that the CollectionBase can contain.

(Herdado de CollectionBase)
Count

Obtém o número de elementos contidos na coleção.Gets the number of elements contained in the collection.

(Herdado de X509CertificateCollection)
InnerList

Obtém uma ArrayList que contém a lista de elementos na instância de CollectionBase.Gets an ArrayList containing the list of elements in the CollectionBase instance.

(Herdado de CollectionBase)
Item[Int32]

Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index.

List

Obtém uma IList que contém a lista de elementos na instância de CollectionBase.Gets an IList containing the list of elements in the CollectionBase instance.

(Herdado de CollectionBase)

Métodos

Add(X509Certificate)

Adiciona um X509Certificate com o valor especificado ao X509CertificateCollection atual.Adds an X509Certificate with the specified value to the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
Add(X509Certificate2)

Adiciona um objeto ao final do X509Certificate2Collection.Adds an object to the end of the X509Certificate2Collection.

AddRange(X509Certificate[])

Copia os elementos de uma matriz do tipo X509Certificate no final da X509CertificateCollection atual.Copies the elements of an array of type X509Certificate to the end of the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
AddRange(X509Certificate2[])

Adiciona vários objetos X509Certificate2 em uma matriz ao objeto X509Certificate2Collection.Adds multiple X509Certificate2 objects in an array to the X509Certificate2Collection object.

AddRange(X509Certificate2Collection)

Adiciona vários objetos X509Certificate2 que estão em um objeto X509Certificate2Collection em outro objeto X509Certificate2Collection.Adds multiple X509Certificate2 objects in an X509Certificate2Collection object to another X509Certificate2Collection object.

AddRange(X509CertificateCollection)

Copia os elementos da X509CertificateCollection no final da X509CertificateCollection atual.Copies the elements of the specified X509CertificateCollection to the end of the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
Clear()

Remove todos os itens da coleção.Removes all items from the collection.

(Herdado de X509CertificateCollection)
Contains(X509Certificate)

Obtém um valor que indica se a X509CertificateCollection atual contém o X509Certificate especificado.Gets a value indicating whether the current X509CertificateCollection contains the specified X509Certificate.

(Herdado de X509CertificateCollection)
Contains(X509Certificate2)

Determina se o objeto X509Certificate2Collection contém um certificado específico.Determines whether the X509Certificate2Collection object contains a specific certificate.

CopyTo(X509Certificate[], Int32)

Copia os valores do X509Certificate que estão na X509CertificateCollection atual para uma instância Array unidimensional no índice especificado.Copies the X509Certificate values in the current X509CertificateCollection to a one-dimensional Array instance at the specified index.

(Herdado de X509CertificateCollection)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
Export(X509ContentType)

Exporta as informações do certificado X.509 para uma matriz de bytes.Exports X.509 certificate information into a byte array.

Export(X509ContentType, String)

Exporta as informações do certificado X.509 para uma matriz de bytes usando uma senha.Exports X.509 certificate information into a byte array using a password.

Find(X509FindType, Object, Boolean)

Pesquisa um objeto X509Certificate2Collection usando critérios de pesquisa especificados pela enumeração X509FindType e pelo objeto findValue.Searches an X509Certificate2Collection object using the search criteria specified by the X509FindType enumeration and the findValue object.

GetEnumerator()

Retorna um enumerador que pode iterar no objeto X509Certificate2Collection.Returns an enumerator that can iterate through a X509Certificate2Collection object.

GetHashCode()

Cria um valor de hash baseado e em todos os valores contidos na X509CertificateCollection atual.Builds a hash value based on all values contained in the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Import(Byte[])

Importa um certificado na forma de uma matriz de bytes em um objeto X509Certificate2Collection.Imports a certificate in the form of a byte array into a X509Certificate2Collection object.

Import(Byte[], String, X509KeyStorageFlags)

Importa um certificado, na forma de uma matriz de bytes que exige uma senha para acessar o certificado em um objeto X509Certificate2Collection.Imports a certificate, in the form of a byte array that requires a password to access the certificate, into a X509Certificate2Collection object.

Import(ReadOnlySpan<Byte>)

Importa para esta coleção os certificados dos dados fornecidos.Imports the certificates from the provided data into this collection.

Import(ReadOnlySpan<Byte>, ReadOnlySpan<Char>, X509KeyStorageFlags)

Importa para esta coleção os certificados dos dados fornecidos.Imports the certificates from the provided data into this collection.

Import(ReadOnlySpan<Byte>, String, X509KeyStorageFlags)

Importa para esta coleção os certificados dos dados fornecidos.Imports the certificates from the provided data into this collection.

Import(String)

Importa um arquivo de certificado para um objeto X509Certificate2Collection.Imports a certificate file into a X509Certificate2Collection object.

Import(String, ReadOnlySpan<Char>, X509KeyStorageFlags)

Importa para esta coleção os certificados do arquivo especificado.Imports the certificates from the specified file a into this collection.

Import(String, String, X509KeyStorageFlags)

Importa um arquivo de certificado que exige uma senha em um objeto X509Certificate2Collection.Imports a certificate file that requires a password into a X509Certificate2Collection object.

ImportFromPem(ReadOnlySpan<Char>)

Importa uma coleção dos certificados codificados por PEM do RFC 7468.Imports a collection of RFC 7468 PEM-encoded certificates.

ImportFromPemFile(String)

Importa uma coleção dos certificados codificados por PEM do RFC 7468.Imports a collection of RFC 7468 PEM-encoded certificates.

IndexOf(X509Certificate)

Retorna o índice do X509Certificate especificado na X509CertificateCollection atual.Returns the index of the specified X509Certificate in the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
Insert(Int32, X509Certificate)

Insere um X509Certificate na X509CertificateCollection atual no índice especificado.Inserts a X509Certificate into the current X509CertificateCollection at the specified index.

(Herdado de X509CertificateCollection)
Insert(Int32, X509Certificate2)

Insere um objeto no objeto X509Certificate2Collection no índice especificado.Inserts an object into the X509Certificate2Collection object at the specified index.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnClear()

Executa processos personalizados adicionais ao limpar o conteúdo da instância CollectionBase.Performs additional custom processes when clearing the contents of the CollectionBase instance.

(Herdado de CollectionBase)
OnClearComplete()

Executa processos adicionais personalizados após limpar o conteúdo da instância CollectionBase.Performs additional custom processes after clearing the contents of the CollectionBase instance.

(Herdado de CollectionBase)
OnInsert(Int32, Object)

Executa os processos personalizados adicionais antes de inserir um novo elemento na instância CollectionBase.Performs additional custom processes before inserting a new element into the CollectionBase instance.

(Herdado de CollectionBase)
OnInsertComplete(Int32, Object)

Executa processos personalizados adicionais após inserir um novo elemento na instância de CollectionBase.Performs additional custom processes after inserting a new element into the CollectionBase instance.

(Herdado de CollectionBase)
OnRemove(Int32, Object)

Executa processos personalizados adicionais ao remover um elemento da instância CollectionBase.Performs additional custom processes when removing an element from the CollectionBase instance.

(Herdado de CollectionBase)
OnRemoveComplete(Int32, Object)

Executa processos personalizados adicionais após remover um elemento da instância de CollectionBase.Performs additional custom processes after removing an element from the CollectionBase instance.

(Herdado de CollectionBase)
OnSet(Int32, Object, Object)

Executa processos personalizados adicionais antes de definir um valor na instância CollectionBase.Performs additional custom processes before setting a value in the CollectionBase instance.

(Herdado de CollectionBase)
OnSetComplete(Int32, Object, Object)

Executa processos personalizados adicionais após configurar um valor na instância de CollectionBase.Performs additional custom processes after setting a value in the CollectionBase instance.

(Herdado de CollectionBase)
OnValidate(Object)

Executa processos personalizados adicionais ao validar um valor.Performs additional custom processes when validating a value.

(Herdado de X509CertificateCollection)
Remove(X509Certificate)

Remove um X509Certificate específico da X509CertificateCollection atual.Removes a specific X509Certificate from the current X509CertificateCollection.

(Herdado de X509CertificateCollection)
Remove(X509Certificate2)

Remove a primeira ocorrência de um certificado do objeto X509Certificate2Collection.Removes the first occurrence of a certificate from the X509Certificate2Collection object.

RemoveAt(Int32)

Remove o elemento no índice especificado.Removes the element at the specified index.

(Herdado de X509CertificateCollection)
RemoveRange(X509Certificate2[])

Remove vários objetos X509Certificate2 em uma matriz de um objeto X509Certificate2Collection.Removes multiple X509Certificate2 objects in an array from an X509Certificate2Collection object.

RemoveRange(X509Certificate2Collection)

Remove vários objetos X509Certificate2 em um objeto X509Certificate2Collection de outro objeto X509Certificate2Collection.Removes multiple X509Certificate2 objects in an X509Certificate2Collection object from another X509Certificate2Collection object.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32)

Copia toda a coleção em uma matriz unidimensional compatível a partir do índice especificado da matriz de destino.Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array.

(Herdado de X509CertificateCollection)
ICollection.IsSynchronized

Obtém um valor que indica se o acesso à coleção é sincronizado (thread-safe).Gets a value indicating whether access to the collection is synchronized (thread safe).

(Herdado de X509CertificateCollection)
ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso à coleção.Gets an object that can be used to synchronize access to the collection.

(Herdado de X509CertificateCollection)
IEnumerable.GetEnumerator()

Retorna um enumerador que itera pela coleção.Returns an enumerator that iterates through the collection.

(Herdado de X509CertificateCollection)
IList.Add(Object)

Adiciona o objeto ao final da coleção.Adds an object to the end of the collection.

(Herdado de X509CertificateCollection)
IList.Contains(Object)

Determina se a coleção contém um elemento específico.Determines whether the collection contains a specific element.

(Herdado de X509CertificateCollection)
IList.IndexOf(Object)

Pesquisa o objeto especificado e retorna o índice de base zero da primeira ocorrência dentro da coleção.Searches for the specified object and returns the zero-based index of the first occurrence within the collection.

(Herdado de X509CertificateCollection)
IList.Insert(Int32, Object)

Insere um elemento na coleção no índice especificado.Inserts an element into the collection at the specified index.

(Herdado de X509CertificateCollection)
IList.IsFixedSize

Obtém um valor que indica se a coleção tem um tamanho fixo.Gets a value indicating whether the collection has a fixed size.

(Herdado de X509CertificateCollection)
IList.IsReadOnly

Obtém um valor que indica se a coleção é somente leitura.Gets a value indicating whether the collection is read-only.

(Herdado de X509CertificateCollection)
IList.Item[Int32]

Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index.

(Herdado de X509CertificateCollection)
IList.Remove(Object)

Remove a primeira ocorrência de um objeto específico da coleção.Removes the first occurrence of a specific object from the collection.

(Herdado de X509CertificateCollection)

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a