X509Certificate2.ValidTo Property

Gets the date and time, on the local computer, when the certificate expires.

System.Security.Cryptography.X509Certificates
public DateTime ValidTo { get; }

Property Value

DateTime
A DateTime object that contains the expiration date and time of the certificate.

Remarks

The ValidTo property represents the expiration date of the X.509 certificate. This property is crucial for validating the authenticity and trustworthiness of a certificate, as expired certificates are no longer considered valid.

When you retrieve the value of this property, it is converted to the local time of the computer. This conversion accounts for any time zone differences between the certificate's issuance location and the local machine.

Tip: Always compare the current date and time with the ValidTo property to ensure that a certificate is still valid before using it for cryptographic operations.

Requirements

Namespace:
System.Security.Cryptography.X509Certificates
Assembly:
System.Security.Cryptography.X509Certificates.dll
.NET Framework versions:
Supported in: 4.5, 4.0, 3.5, 3.0, 2.0

See Also

Example

The following code example demonstrates how to retrieve the expiration date of an X.509 certificate.

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

public class CertificateExpiration
{
    public static void Main(string[] args)
    {
        try
        {
            // Replace with a valid certificate thumbprint or path
            string certificateThumbprint = "YOUR_CERTIFICATE_THUMBPRINT";
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection certificates = store.Certificates.Find(
                X509FindType.FindByThumbprint, certificateThumbprint, false);

            if (certificates.Count > 0)
            {
                X509Certificate2 cert = certificates[0];
                DateTime expirationDate = cert.ValidTo;

                Console.WriteLine($"Certificate: {cert.Subject}");
                Console.WriteLine($"Expires on: {expirationDate}");

                if (expirationDate < DateTime.Now)
                {
                    Console.WriteLine("This certificate has expired.");
                }
                else
                {
                    Console.WriteLine("This certificate is still valid.");
                }
            }
            else
            {
                Console.WriteLine("Certificate not found.");
            }

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