MSDN Library - System.Net.Security

X509Certificate2.ValidUntil Property

Gets the date and time when the certificate expires.

public DateTime ValidUntil { get; }

Remarks

The ValidUntil property represents the expiration date and time of the X.509 certificate. This property is of type DateTime and provides the precise moment up to which the certificate is considered valid. After this date and time, the certificate is considered expired and should no longer be trusted for cryptographic operations.

When working with certificates, it is crucial to check their validity period to ensure secure communication and operations. An expired certificate can lead to connection failures, security warnings, or rejection by relying parties.

Example

The following code example demonstrates how to retrieve the expiration date and time of an X509Certificate2 object.


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

public class CertificateExpirationChecker
{
    public static void Main(string[] args)
    {
        try
        {
            // Load a certificate (replace with your certificate loading logic)
            // For demonstration, we'll try to get the current user's personal store certificate.
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            if (store.Certificates.Count > 0)
            {
                X509Certificate2 certificate = store.Certificates[0]; // Get the first certificate

                DateTime expirationDate = certificate.ValidUntil;

                Console.WriteLine($"Certificate Name: {certificate.SubjectName.Name}");
                Console.WriteLine($"Certificate Expires On: {expirationDate.ToString("yyyy-MM-dd HH:mm:ss")}");

                if (DateTime.UtcNow > expirationDate)
                {
                    Console.WriteLine("This certificate has expired.");
                }
                else
                {
                    Console.WriteLine("This certificate is still valid.");
                }
            }
            else
            {
                Console.WriteLine("No certificates found in the CurrentUser's Personal store.");
            }

            store.Close();
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine($"Error accessing certificates: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}
        

Requirements

Assembly DLL
System.Security.Cryptography.X509Certificates System.Security.Cryptography.X509Certificates.dll

See Also

Note: The example code provided is for illustrative purposes. Ensure proper error handling and certificate management practices are followed in production environments.