- 1 year ago
How to access the web credentials from a .NET app?
Comment
1 / 1
You can access web credentials from a .NET app by using the System.Net.CredentialCache
class. This class is used to store and retrieve credentials for use in web requests. Here is an example of how you can retrieve credentials for a given URI:
csharpusing System;
using System.Net;
class Program
{
static void Main(string[] args)
{
string uri = "https://example.com";
CredentialCache cache = new CredentialCache();
Uri targetUri = new Uri(uri);
// Retrieve the credentials for the URI
NetworkCredential creds = cache.GetCredential(targetUri, "Basic");
if (creds != null)
{
Console.WriteLine("User: {0}", creds.UserName);
Console.WriteLine("Password: {0}", creds.Password);
}
else
{
Console.WriteLine("No credentials found.");
}
}
}
In this example, the CredentialCache
object is used to retrieve the credentials for the given URI. The GetCredential
method takes a Uri
object and a string representing the authentication type (e.g. "Basic", "Digest", "NTLM", etc.). If credentials are found for the URI, they are returned as a NetworkCredential
object, which contains the username and password for the credentials. If no credentials are found, GetCredential
returns null.