X509Store 類別

定義

表示 X.509 存放區,這個存放區是保存和管理憑證的實體存放區。Represents an X.509 store, which is a physical store where certificates are persisted and managed. 這個類別無法被繼承。This class cannot be inherited.

public ref class X509Store sealed : IDisposable
public sealed class X509Store : IDisposable
type X509Store = class
    interface IDisposable
Public NotInheritable Class X509Store
Implements IDisposable
繼承
X509Store
實作

範例

本章節包含兩個範例。This section contains two examples. 第一個範例會示範如何開啟標準的 x.509 存放區, 並列出每個中的憑證數目。The first example demonstrates how you can open standard X.509 stores and list the number of certificates in each.

第二個範例會示範如何新增和移除單一憑證和憑證範圍。The second example demonstrates how you can add and remove single certificates and ranges of certificates.

範例1Example 1

這個範例會嘗試在目前電腦上的每個標準位置中開啟每個標準存放區。This example tries to open each standard store in each standard location on the current computer. 它會列印摘要, 其中顯示每個商店是否存在, 如果是的話, 它包含的憑證數目。It prints a summary that shows whether each store exists and, if so, the number of certificates it contains.

此範例會針對X509Store標準名稱和標準位置的每個組合建立一個物件。The example creates an X509Store object for each combination of standard name and standard location. 它會Open OpenFlags.OpenExistingOnly使用旗標來呼叫方法, 只有在實體存放區已存在時才會開啟。It calls the Open method with the OpenFlags.OpenExistingOnly flag, which opens the physical store only if it already exists. 如果實體存放區存在, 則此範例會Name使用Location、和Certificates屬性來顯示存放區中的憑證數目。If the physical store exists, the example uses the Name, Location, and Certificates properties to display the number of certificates in the store.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class Example
{
    static void Main()
    {
        Console.WriteLine("\r\nExists Certs Name and Location");
        Console.WriteLine("------ ----- -------------------------");

        foreach (StoreLocation storeLocation in (StoreLocation[]) 
            Enum.GetValues(typeof(StoreLocation)))
        {
            foreach (StoreName storeName in (StoreName[]) 
                Enum.GetValues(typeof(StoreName)))
            {
                X509Store store = new X509Store(storeName, storeLocation);

                try
                {
                    store.Open(OpenFlags.OpenExistingOnly);

                    Console.WriteLine("Yes    {0,4}  {1}, {2}", 
                        store.Certificates.Count, store.Name, store.Location);
                }   
                catch (CryptographicException)
                {
                    Console.WriteLine("No           {0}, {1}", 
                        store.Name, store.Location);
                }
            }
            Console.WriteLine();
        }
    }
}

/* This example produces output similar to the following:

Exists Certs Name and Location
------ ----- -------------------------
Yes       1  AddressBook, CurrentUser
Yes      25  AuthRoot, CurrentUser
Yes     136  CA, CurrentUser
Yes      55  Disallowed, CurrentUser
Yes      20  My, CurrentUser
Yes      36  Root, CurrentUser
Yes       0  TrustedPeople, CurrentUser
Yes       1  TrustedPublisher, CurrentUser

No           AddressBook, LocalMachine
Yes      25  AuthRoot, LocalMachine
Yes     131  CA, LocalMachine
Yes      55  Disallowed, LocalMachine
Yes       3  My, LocalMachine
Yes      36  Root, LocalMachine
Yes       0  TrustedPeople, LocalMachine
Yes       1  TrustedPublisher, LocalMachine

 */
Option Strict On

Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Module Example

    Sub Main()

        Console.WriteLine(vbCrLf & "Exists Certs Name and Location")
        Console.WriteLine("------ ----- -------------------------")

        For Each storeLocation As StoreLocation In _
                CType([Enum].GetValues(GetType(StoreLocation)), StoreLocation())

            For Each storeName As StoreName In _
                    CType([Enum].GetValues(GetType(StoreName)), StoreName())

                Dim store As New X509Store(StoreName, StoreLocation)

                Try
                    store.Open(OpenFlags.OpenExistingOnly)
                    Console.WriteLine("Yes    {0,4}  {1}, {2}", _
                        store.Certificates.Count, store.Name, store.Location)
                Catch e As CryptographicException
                    Console.WriteLine("No           {0}, {1}", _
                        store.Name, store.Location)
                End Try
            Next

            Console.WriteLine()
        Next
    End Sub
End Module

' This example produces output similar to the following:

'Exists Certs Name and Location
'------ ----- -------------------------
'Yes       1  AddressBook, CurrentUser
'Yes      25  AuthRoot, CurrentUser
'Yes     136  CA, CurrentUser
'Yes      55  Disallowed, CurrentUser
'Yes      20  My, CurrentUser
'Yes      36  Root, CurrentUser
'Yes       0  TrustedPeople, CurrentUser
'Yes       1  TrustedPublisher, CurrentUser

'No           AddressBook, LocalMachine
'Yes      25  AuthRoot, LocalMachine
'Yes     131  CA, LocalMachine
'Yes      55  Disallowed, LocalMachine
'Yes       3  My, LocalMachine
'Yes      36  Root, LocalMachine
'Yes       0  TrustedPeople, LocalMachine
'Yes       1  TrustedPublisher, LocalMachine

範例2Example 2

這個範例會開啟 x.509 憑證存放區、新增和刪除憑證, 然後關閉存放區。This example opens an X.509 certificate store, adds and deletes certificates, and then closes the store. 它假設您有三個要在本機存放區中新增和移除的憑證。It assumes that you have three certificates to add to and remove from a local store.

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

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;
int main()
{
   
   //Create new X509 store called teststore from the local certificate store.
   X509Store ^ store = gcnew X509Store( "teststore",StoreLocation::CurrentUser );
   store->Open( OpenFlags::ReadWrite );
   X509Certificate2 ^ certificate = gcnew X509Certificate2;
   
   //Create certificates from certificate files.
   //You must put in a valid path to three certificates in the following constructors.
   X509Certificate2 ^ certificate1 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   X509Certificate2 ^ certificate2 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   X509Certificate2 ^ certificate5 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   
   //Create a collection and add two of the certificates.
   X509Certificate2Collection ^ collection = gcnew X509Certificate2Collection;
   collection->Add( certificate2 );
   collection->Add( certificate5 );
   
   //Add certificates to the store.
   store->Add( certificate1 );
   store->AddRange( collection );
   X509Certificate2Collection ^ storecollection = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "Store name: {0}", store->Name );
   Console::WriteLine( "Store location: {0}", store->Location );
   System::Collections::IEnumerator^ myEnum = storecollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum->Current);
      Console::WriteLine( "certificate name: {0}", x509->Subject );
   }

   
   //Remove a certificate.
   store->Remove( certificate1 );
   X509Certificate2Collection ^ storecollection2 = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "{1}Store name: {0}", store->Name, Environment::NewLine );
   System::Collections::IEnumerator^ myEnum1 = storecollection2->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum1->Current);
      Console::WriteLine( "certificate name: {0}", x509->Subject );
   }

   
   //Remove a range of certificates.
   store->RemoveRange( collection );
   X509Certificate2Collection ^ storecollection3 = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "{1}Store name: {0}", store->Name, Environment::NewLine );
   if ( storecollection3->Count == 0 )
   {
      Console::WriteLine( "Store contains no certificates." );
   }
   else
   {
      System::Collections::IEnumerator^ myEnum2 = storecollection3->GetEnumerator();
      while ( myEnum2->MoveNext() )
      {
         X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum2->Current);
         Console::WriteLine( "certificate name: {0}", x509->Subject );
      }
   }

   
   //Close the store.
   store->Close();
}

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

public class X509store2
{
    public static void Main (string[] args)
    {
        //Create new X509 store called teststore from the local certificate store.
        X509Store store = new X509Store ("teststore", StoreLocation.CurrentUser);
        store.Open (OpenFlags.ReadWrite);
        X509Certificate2 certificate = new X509Certificate2 ();

        //Create certificates from certificate files.
        //You must put in a valid path to three certificates in the following constructors.
        X509Certificate2 certificate1 = new X509Certificate2 ("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate2 = new X509Certificate2 ("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate5 = new X509Certificate2 ("c:\\mycerts\\*****.cer");

        //Create a collection and add two of the certificates.
        X509Certificate2Collection collection = new X509Certificate2Collection ();
        collection.Add (certificate2);
        collection.Add (certificate5);

        //Add certificates to the store.
        store.Add (certificate1);
        store.AddRange (collection);

        X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("Store name: {0}", store.Name);
        Console.WriteLine ("Store location: {0}", store.Location);
        foreach (X509Certificate2 x509 in storecollection)
        {
            Console.WriteLine("certificate name: {0}",x509.Subject);
        }

        //Remove a certificate.
        store.Remove (certificate1);
        X509Certificate2Collection storecollection2 = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("{1}Store name: {0}", store.Name, Environment.NewLine);
        foreach (X509Certificate2 x509 in storecollection2)
        {
            Console.WriteLine ("certificate name: {0}", x509.Subject);
        }

        //Remove a range of certificates.
        store.RemoveRange (collection);
        X509Certificate2Collection storecollection3 = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("{1}Store name: {0}", store.Name, Environment.NewLine);
        if (storecollection3.Count == 0)
        {
            Console.WriteLine ("Store contains no certificates.");
        }
        else
        {
            foreach (X509Certificate2 x509 in storecollection3)
            {
                Console.WriteLine ("certificate name: {0}", x509.Subject);
            }
        }

        //Close the store.
        store.Close ();
    }	
}
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.IO



Class X509store2

    Shared Sub Main(ByVal args() As String)
        'Create new X509 store called teststore from the local certificate store.
        Dim store As New X509Store("teststore", StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadWrite)
        Dim certificate As New X509Certificate2()

        'Create certificates from certificate files.
        'You must put in a valid path to three certificates in the following constructors.
        Dim certificate1 As New X509Certificate2("c:\mycerts\*****.cer")
        Dim certificate2 As New X509Certificate2("c:\mycerts\*****.cer")
        Dim certificate5 As New X509Certificate2("c:\mycerts\*****.cer")

        'Create a collection and add two of the certificates.
        Dim collection As New X509Certificate2Collection()
        collection.Add(certificate2)
        collection.Add(certificate5)

        'Add certificates to the store.
        store.Add(certificate1)
        store.AddRange(collection)

        Dim storecollection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("Store name: {0}", store.Name)
        Console.WriteLine("Store location: {0}", store.Location)
        Dim x509 As X509Certificate2
        For Each x509 In storecollection
            Console.WriteLine("certificate name: {0}", x509.Subject)
        Next x509

        'Remove a certificate.
        store.Remove(certificate1)
        Dim storecollection2 As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine)
        Dim x509a As X509Certificate2
        For Each x509a In storecollection2
            Console.WriteLine("certificate name: {0}", x509a.Subject)
        Next x509a

        'Remove a range of certificates.
        store.RemoveRange(collection)
        Dim storecollection3 As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine)
        If storecollection3.Count = 0 Then
            Console.WriteLine("Store contains no certificates.")
        Else
            Dim x509b As X509Certificate2
            For Each x509b In storecollection3
                Console.WriteLine("certificate name: {0}", x509b.Subject)
            Next x509b
        End If

        'Close the store.
        store.Close()

    End Sub
End Class

備註

使用此類別來處理 x.509 存放區。Use this class to work with an X.509 store.

重要

從開始IDisposable , 這個型別會實作為介面。 .NET Framework 4.6.NET Framework 4.6Starting with the .NET Framework 4.6.NET Framework 4.6, this type implements the IDisposable interface. 當您完成使用型別時,您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

針對以.NET Framework 4.5.2.NET Framework 4.5.2和舊版為目標的應用程式X509Store , IDisposable類別不會執行介面, 因此不會有Dispose方法。For apps that target the .NET Framework 4.5.2.NET Framework 4.5.2 and earlier versions, the X509Store class does not implement the IDisposable interface and therefore does not have a Dispose method.

建構函式

X509Store()

使用目前使用者存放區的個人憑證,初始化 X509Store 類別的新執行個體。Initializes a new instance of the X509Store class using the personal certificates of the current user store.

X509Store(IntPtr)

使用 X509Store 存放區的 Intptr 控制代碼,初始化 HCERTSTORE 類別的新執行個體。Initializes a new instance of the X509Store class using an Intptr handle to an HCERTSTORE store.

X509Store(StoreLocation)

使用指定的 StoreLocation 值,初始化 X509Store 類別的新執行個體。Initializes a new instance of the X509Store class using the specified StoreLocation value.

X509Store(StoreName)

使用指定的 StoreName 值,初始化 X509Store 類別的新執行個體。Initializes a new instance of the X509Store class using the specified StoreName value.

X509Store(StoreName, StoreLocation)

使用指定的 X509StoreStoreName 值,初始化 StoreLocation 類別的新執行個體。Initializes a new instance of the X509Store class using the specified StoreName and StoreLocation values.

X509Store(StoreName, StoreLocation, OpenFlags)
X509Store(String)

使用指定的存放區名稱,初始化 X509Store 類別的新執行個體。Initializes a new instance of the X509Store class using the specified store name.

X509Store(String, StoreLocation)

使用表示 X509Store 列舉之值和 StoreName 列舉之值的字串,初始化 StoreLocation 類別的新執行個體。Initializes a new instance of the X509Store class using a string that represents a value from the StoreName enumeration and a value from the StoreLocation enumeration.

X509Store(String, StoreLocation, OpenFlags)

屬性

Certificates

傳回位於 X.509 憑證存放區的憑證集合。Returns a collection of certificates located in an X.509 certificate store.

IsOpen
Location

取得 X.509 憑證存放區的位置。Gets the location of the X.509 certificate store.

Name

取得 X.509 憑證存放區的名稱。Gets the name of the X.509 certificate store.

StoreHandle

取得 IntPtr 存放區的 HCERTSTORE 控制代碼。Gets an IntPtr handle to an HCERTSTORE store.

方法

Add(X509Certificate2)

將憑證加入 X.509 憑證存放區。Adds a certificate to an X.509 certificate store.

AddRange(X509Certificate2Collection)

將憑證集合加入 X.509 憑證存放區。Adds a collection of certificates to an X.509 certificate store.

Close()

關閉 X.509 憑證存放區。Closes an X.509 certificate store.

Dispose()

釋放這個 X509Store 所使用的資源。Releases the resources used by this X509Store.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
Open(OpenFlags)

開啟 X.509 憑證存放區或建立新的存放區 (視 OpenFlags 旗標設定而定)。Opens an X.509 certificate store or creates a new store, depending on OpenFlags flag settings.

Remove(X509Certificate2)

移除 X.509 憑證存放區中的憑證。Removes a certificate from an X.509 certificate store.

RemoveRange(X509Certificate2Collection)

移除 X.509 憑證存放區中某個範圍的憑證。Removes a range of certificates from an X.509 certificate store.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於