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
-
NetworkCredential()
Initializes a new instance of the
NetworkCredentialclass. -
NetworkCredential(string userName, string password)
Initializes a new instance of the
NetworkCredentialclass with the specified user name and password. -
NetworkCredential(string userName, string password, string domain)
Initializes a new instance of the
NetworkCredentialclass with the specified user name, password, and domain.
Properties
-
Domain
stringGets or sets the domain associated with the network credential.
-
Password
stringGets or sets the password associated with the network credential.
-
UserName
stringGets or sets the user name associated with the network credential.
Methods
-
GetCredential(string challengeUri, string authType)
ICredentialsReturns this instance of
NetworkCredential. -
ToString()
stringReturns a string that represents the current object.
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