Getting Information about an X509Certificate's Key Container

One of the more common things a lot of people want to do with their X509Certificate2 is figure out what key container its keys are stored in.  You can access this information relatively trivially via the PublicKey property of the X509Certificate2 object:

/// <summary>
/// Get information about the key container a certificate is stored in
/// </summary>
public static CspKeyContainerInfo GetKeyConatinerInformation(X509Certificate2 certificate)
{
    if (certificate == null)
        throw new ArgumentNullException("certificate");

    ICspAsymmetricAlgorithm key = certificate.PublicKey.Key as ICspAsymmetricAlgorithm;
    if (key == null)
        throw new InvalidOperationException("Unknown key type");

    return key.CspKeyContainerInfo;
}

Here we get the ICspAsymmetricAlgorithm representing the key from the public key, which should work for both RSA and DSS certificates.  From there we can simply pull the CspKeyContainerInfo object and get basically anything we want to know about the key container.  Specifically, the KeyContainerName, KeyNumber, ProviderName, ProviderType, HardwareDevice, and Exportable properties tend to be the most interesting.

Note that this trick will not work with the PrivateKey property of the X509Certificate2, since the private key returned is actually a copy of the key associated with the certificate.