Description
The CredentialCache class stores credentials for multiple Internet resources. Applications that need to access multiple resources can store the credentials for those resources in a CredentialCache instance that then provides the proper set of credentials for a given resource when required. When the GetCredential method is called, it compares the URI and authentication type provided with those stored in the cache, and returns the first set of credentials that match.
Example
using System;
using System.Net;
using System.Collections;
/// <summary>
/// Creates two new NetworkCredential instances, adds them to a
/// CredentialCache and then removes one, showing the contents
/// of the CredentialCache cache at each stage
/// </summary>
public class CredentialCacheSample
{
private static void ShowContents(CredentialCache cc,
String caption)
{
Console.WriteLine();
Console.WriteLine(caption + ":");
foreach (NetworkCredential found in cc)
{
Console.WriteLine("User:'{0}'\t Password:'{1}'\t "
+ "Domain:'{2}'", found.UserName,
found.Password, found.Domain);
}
}
public static void Main()
{
Console.WriteLine("DefaultCredentials = '{0}'",
CredentialCache.DefaultCredentials);
NetworkCredential nc1 = new
NetworkCredential("test", "secret");
NetworkCredential nc2 = new
NetworkCredential("local", "moresecret", "mydomain");
Uri path = new Uri("http://mysite.com");
CredentialCache cc = new CredentialCache();
cc.Add(path, "BASIC", nc1);
cc.Add(path, "NTLM", nc2);
ShowContents(cc, "After adding two credentials");
cc.Remove(path, "BASIC");
ShowContents(cc, "After removing BASIC credential");
}
}
The output is
DefaultCredentials = 'System.Net.SystemNetworkCredential'
After adding two credentials:
User:'test' Password:'secret' Domain:''
User:'local' Password:'moresecret' Domain:'mydomain'
After removing BASIC credential:
User:'local' Password:'moresecret' Domain:'mydomain'
|