X509Certificate2.DnsNames Property

Gets the collection of DNS names associated with the certificate.

public System.Security.Cryptography.OidCollection DnsNames { get; }

Property Value

Type: System.Security.Cryptography.OidCollection

A collection of Object Identifiers (OIDs) representing the DNS names in the certificate's subject alternative name extension.

Remarks

The DnsNames property retrieves DNS names from the Subject Alternative Name (SAN) extension of an X.509 certificate. This extension allows multiple DNS names to be associated with a single certificate, which is crucial for secure communication with multiple hostnames.

If the certificate does not contain a Subject Alternative Name extension, or if the extension does not contain any DNS name entries, this property will return an empty collection.

The collection returned by this property contains Oid objects, where the Value property of each Oid represents a DNS name string.

Example

The following code example demonstrates how to retrieve and iterate through the DNS names of an X.509 certificate.

C#
using System;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

public class CertificateDnsChecker
{
    public static void DisplayDnsNames(X509Certificate2 certificate)
    {
        if (certificate == null)
        {
            Console.WriteLine("Certificate is null.");
            return;
        }

        Console.WriteLine($"Certificate Subject: {certificate.Subject}");

        var dnsNames = certificate.DnsNames;

        if (dnsNames != null && dnsNames.Count > 0)
        {
            Console.WriteLine("DNS Names:");
            foreach (Oid oid in dnsNames)
            {
                Console.WriteLine($"- {oid.Value}");
            }
        }
        else
        {
            Console.WriteLine("No DNS names found in the certificate.");
        }
    }

    // Example usage (assuming you have a certificate object)
    public static void Main(string[] args)
    {
        try
        {
            // Replace with your actual certificate loading logic
            // For demonstration, create a dummy certificate
            // In a real scenario, you would load from store or file
            var dummyCert = new X509Certificate2("path/to/your/certificate.pfx", "your_password");
            DisplayDnsNames(dummyCert);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
                    

Requirements

.NET Framework

Supported in: 5.0, 4.8, 4.7.2, 4.7.1, 4.7, 4.6.2, 4.6.1, 4.6, 4.5.2, 4.5.1, 4.5, 4.0

.NET

Supported in: Core 1.0, 1.1, 2.0, 3.0, 3.1, 5.0, 6.0, 7.0, 8.0

Platforms

Supported in: Windows, Linux, macOS

See Also