System.Net.NetworkCredential

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

Summary

Represents a user's network credentials, such as a user name and password, for basic authentication.

Properties

  • Domain
    public string Domain { get; set; }
    Gets or sets the domain of the network credential.
  • Password
    public string Password { get; set; }
    Gets or sets the password for the network credential.
  • UserName
    public string UserName { get; set; }
    Gets or sets the user name for the network credential.

Constructors

  • NetworkCredential
    public NetworkCredential()
    Initializes a new instance of the NetworkCredential class.
  • NetworkCredential
    public NetworkCredential(string userName, string password)
    Initializes a new instance of the NetworkCredential class with the specified user name and password.
  • NetworkCredential
    public NetworkCredential(string userName, string password, string domain)
    Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.

Methods

  • GetCredential
    public override System.Net.ICredentials GetCredential()
    Returns this instance of NetworkCredential.
  • ToString
    public override string ToString()
    Returns a string representation of the NetworkCredential object.

Remarks

The NetworkCredential class is used to supply network credentials to various classes in the System.Net namespace, such as FtpWebRequest, HttpWebRequest, and SmtpClient.

It's important to handle sensitive information like passwords securely. Consider using mechanisms like Windows Integrated Authentication or storing credentials securely when possible.

Example


using System;
using System.Net;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a NetworkCredential object
        NetworkCredential credentials = new NetworkCredential("myUsername", "myPassword", "myDomain");

        // You can then use these credentials with classes like HttpWebRequest
        // HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com");
        // request.Credentials = credentials;

        Console.WriteLine($"Username: {credentials.UserName}");
        Console.WriteLine($"Domain: {credentials.Domain}");
        // Password should ideally not be logged or displayed directly
        // Console.WriteLine($"Password: {credentials.Password}");
    }
}