CredentialCache Class
Collapse the table of content
Expand the table of content

CredentialCache Class


Provides storage for multiple credentials.

Namespace:   System.Net
Assembly:  System (in System.dll)


public class CredentialCache : ICredentials, ICredentialsByHost, 


Creates a new instance of the CredentialCache class.


Gets the system credentials of the application.


Gets the network credentials of the current security context.

System_CAPS_pubmethodAdd(String, Int32, String, NetworkCredential)

Adds a NetworkCredential instance for use with SMTP to the credential cache and associates it with a host computer, port, and authentication protocol. Credentials added using this method are valid for SMTP only. This method does not work for HTTP or FTP requests.

System_CAPS_pubmethodAdd(Uri, String, NetworkCredential)

Adds a NetworkCredential instance to the credential cache for use with protocols other than SMTP and associates it with a Uniform Resource Identifier (URI) prefix and authentication protocol.


Determines whether the specified object is equal to the current object.(Inherited from Object.)


Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetCredential(String, Int32, String)

Returns the NetworkCredential instance associated with the specified host, port, and authentication protocol.

System_CAPS_pubmethodGetCredential(Uri, String)

Returns the NetworkCredential instance associated with the specified Uniform Resource Identifier (URI) and authentication type.


Returns an enumerator that can iterate through the CredentialCache instance.


Serves as the default hash function. (Inherited from Object.)


Gets the Type of the current instance.(Inherited from Object.)


Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodRemove(String, Int32, String)

Deletes a NetworkCredential instance from the cache if it is associated with the specified host, port, and authentication protocol.

System_CAPS_pubmethodRemove(Uri, String)

Deletes a NetworkCredential instance from the cache if it is associated with the specified Uniform Resource Identifier (URI) prefix and authentication protocol.


Returns a string that represents the current object.(Inherited from Object.)


Overloaded. Enables parallelization of a query.(Defined by ParallelEnumerable.)


Overloaded. Converts an IEnumerable to an IQueryable.(Defined by Queryable.)


Casts the elements of an IEnumerable to the specified type.(Defined by Enumerable.)


Filters the elements of an IEnumerable based on a specified type.(Defined by Enumerable.)

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 to the Internet resource when required. When the GetCredential method is called, it compares the Uniform Resource Identifier (URI) and authentication type provided with those stored in the cache and returns the first set of credentials that match.

The DefaultCredentials property contains the system credentials of the current security context. For client applications, these represent the user name, password, and domain of the user who is currently logged in. For ASP.NET applications, the default credentials are the user credentials of the logged-in user or the user being impersonated.

Legacy Code Example

The following code example initializes a CredentialCache with multiple security credentials and uses those credentials with a WebRequest.

// Define the namespaces used by this sample.
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace ProcessAsyncStreamSamples
    class SortOutputRedirection
        // Define static variables shared by class methods.
        private static StringBuilder sortOutput = null;
        private static int numOutputLines = 0;

        public static void SortInputListText()
            // Initialize the process and its StartInfo properties.
            // The sort command is a console application that
            // reads and sorts text input.

            Process sortProcess;
            sortProcess = new Process();
            sortProcess.StartInfo.FileName = "Sort.exe";

            // Set UseShellExecute to false for redirection.
            sortProcess.StartInfo.UseShellExecute = false;

            // Redirect the standard output of the sort command.  
            // This stream is read asynchronously using an event handler.
            sortProcess.StartInfo.RedirectStandardOutput = true;
            sortOutput = new StringBuilder("");

            // Set our event handler to asynchronously read the sort output.
            sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);

            // Redirect standard input as well.  This stream
            // is used synchronously.
            sortProcess.StartInfo.RedirectStandardInput = true;

            // Start the process.

            // Use a stream writer to synchronously write the sort input.
            StreamWriter sortStreamWriter = sortProcess.StandardInput;

            // Start the asynchronous read of the sort output stream.

            // Prompt the user for input text lines.  Write each 
            // line to the redirected input stream of the sort command.
            Console.WriteLine("Ready to sort up to 50 lines of text");

            String inputText;
            int numInputLines = 0;
                Console.WriteLine("Enter a text line (or press the Enter key to stop):");

                inputText = Console.ReadLine();
                if (!String.IsNullOrEmpty(inputText))
                    numInputLines ++;
            while (!String.IsNullOrEmpty(inputText) && (numInputLines < 50));
            Console.WriteLine("<end of input stream>");

            // End the input stream to the sort command.

            // Wait for the sort process to write the sorted text lines.

            if (numOutputLines > 0)
                // Write the formatted and sorted output to the console.
                Console.WriteLine(" Sort results = {0} sorted text line(s) ", 
                Console.WriteLine(" No input lines were sorted.");


        private static void SortOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
            // Collect the sort command output.
            if (!String.IsNullOrEmpty(outLine.Data))

                // Add the text to the collected output.
                sortOutput.Append(Environment.NewLine + 
                    "[" + numOutputLines.ToString() + "] - " + outLine.Data);

namespace ProcessAsyncStreamSamples

    class ProcessSampleMain
        /// The main entry point for the application.
        static void Main()
            catch (InvalidOperationException e)

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.1
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
© 2015 Microsoft