X509Certificate2.GetSubjectName Method
public System.Security.Cryptography.X509Certificates.X509Name GetSubjectName()
Retrieves the subject name from the certificate.
Declaration
C#
public X509Name GetSubjectName();
Parameters
This method does not take any parameters.
Return Value
A X509Name object that contains the subject name of the certificate.
Remarks
- The subject name identifies the entity to which the certificate was issued.
- This method returns an X509Name object, which represents the distinguished name (DN) of the certificate's subject.
- The X509Name object contains a collection of relative distinguished names (RDNs) that make up the subject DN.
Exceptions
- PlatformNotSupportedException: The .NET Core and .NET 5+ versions of this API are not supported on all platforms.
Example
The following code example demonstrates how to retrieve and display the subject name of an X.509 certificate.
using System;
using System.Security.Cryptography.X509Certificates;
public class CertificateSubjectName
{
public static void Main(string[] args)
{
try
{
// Assume 'cert' is an initialized X509Certificate2 object.
// For demonstration, we'll load a common certificate from the current user's personal store.
// In a real application, you would obtain the certificate through appropriate means.
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = null;
if (store.Certificates.Count > 0)
{
// Get the first certificate in the store for demonstration
cert = store.Certificates[0];
}
store.Close();
if (cert != null)
{
Console.WriteLine("Certificate Found:");
Console.WriteLine($"Subject Name: {cert.SubjectName.Name}"); // Using the Name property for simpler display
Console.WriteLine($"Raw Subject Name: {cert.SubjectName.RawData}"); // Displaying raw data for inspection
// Alternatively, using GetSubjectName()
X509Name subjectNameObj = cert.GetSubjectName();
Console.WriteLine($"Subject Name (via GetSubjectName): {subjectNameObj.Name}");
// You can also iterate through the RDNs
Console.WriteLine("Relative Distinguished Names:");
foreach (X509Rdn rdn in subjectNameObj.EnumerateRelativeDistinguishedNames())
{
foreach (X509Attribute attribute in rdn)
{
Console.WriteLine($" - {attribute.Oid.FriendlyName}: {attribute.Value}");
}
}
}
else
{
Console.WriteLine("No certificates found in the current user's personal store.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Syntax
C#
public X509Name GetSubjectName();
Visual Basic
Public Function GetSubjectName As X509Name
C++
public:
X509Name^ GetSubjectName();