System.Net.NetworkCredential

Namespace: System.Net

Represents user credentials for network authentication. This class stores the username, password, and domain for network authentication.

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

Constructors

Properties

Methods

Remarks

The NetworkCredential class is used to provide credentials for network authentication protocols such as Basic, Digest, NTLM, and Kerberos. It is commonly used with classes like HttpClient, FtpWebRequest, and HttpWebRequest.

When constructing a NetworkCredential object, it's important to handle sensitive information like passwords securely. Avoid hardcoding passwords directly in your code. Consider using configuration files, secure storage, or prompting the user for credentials.

Examples

Basic Usage

using System.Net;

// Create a new NetworkCredential instance
NetworkCredential credentials = new NetworkCredential("myuser", "mypassword", "mydomain");

// Access properties
Console.WriteLine($"Username: {credentials.UserName}");
Console.WriteLine($"Domain: {credentials.Domain}");
// Password is not typically printed for security reasons

// Using with HttpClient
using (HttpClientHandler handler = new HttpClientHandler())
{
    handler.Credentials = credentials;
    using (HttpClient client = new HttpClient(handler))
    {
        // Make a request to a protected resource
        // var response = await client.GetAsync("http://example.com/protected");
    }
}
                

Without Domain

using System.Net;

NetworkCredential credentials = new NetworkCredential("localuser", "localpassword");
Console.WriteLine($"Username: {credentials.UserName}");
Console.WriteLine($"Domain: {credentials.Domain}"); // Will be null or empty