Connect to network drive with user name and password

.net, c#

Solution

Very elegant solution inspired from this one. This one uses only .Net library and does not need to use any command line or Win32 API.

Code for ready reference:

NetworkCredential theNetworkCredential = new NetworkCredential(@"domain\username", "password");
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(@"\\computer"), "Basic", theNetworkCredential);
string[] theFolders = Directory.GetDirectories(@"\\computer\share");

Problem

How do I supply credential so that I can connect to a network drive in .NET? I’m trying to retrieve files from a network drive and need to supply user credentials to access the drive.

Original source

Related problems