System.Net.NetworkCredential

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

Class Overview

Represents a user's network credentials. This class cannot be inherited.

Remarks

The NetworkCredential class stores the user's name, password, and domain. It is used by classes in the System.Net.Http and System.Net.Sockets namespaces to authenticate to a network resource.

When you create an instance of the NetworkCredential class, you can specify the user's name, password, and domain. If you do not specify these values, they will be obtained from the current user's credentials.

The NetworkCredential class implements the ICryptographicCredential interface, which provides methods for encrypting and decrypting credentials. However, this functionality is not exposed directly by the NetworkCredential class and is typically handled by lower-level security mechanisms.

Example

using System;
using System.Net;

public class Example
{
    public static void Main(string[] args)
    {
        // Create network credentials for a user
        NetworkCredential nc = new NetworkCredential("username", "password", "domain");

        // Access the properties
        Console.WriteLine($"Username: {nc.UserName}");
        Console.WriteLine($"Password: {nc.Password}"); // Note: Accessing password directly is generally discouraged in production
        Console.WriteLine($"Domain: {nc.Domain}");

        // Example with default constructor (uses current user's credentials)
        // NetworkCredential defaultCredentials = new NetworkCredential();
        // Console.WriteLine($"Default Username: {defaultCredentials.UserName}");
    }
}

Constructors

Name Description
NetworkCredential() Initializes a new instance of the NetworkCredential class. This constructor initializes the properties with the credentials of the current user.
NetworkCredential(string userName, string password) Initializes a new instance of the NetworkCredential class with the specified user name and password.
NetworkCredential(string userName, string password, string domain) Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.

Properties

Name Description
Domain Gets or sets the domain for the network credentials.
Password Gets or sets the password for the network credentials.
Note: For security reasons, avoid directly accessing or logging the password in production code.
UserName Gets or sets the user name for the network credentials.

Methods

Name Description
GetCredential(Uri uri, string authType) Returns a NetworkCredential object based on the specified parameters.
This is an abstract method in the base class and must be overridden.
ToString() Returns a string that represents the current object.
(Inherited from Object)

See Also