X509Certificate2.DnsNames Property
Gets the collection of DNS names associated with the certificate.
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.
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}");
}
}
}