Friday, July 24, 2020

Code: C# Accessing network folder with Username and password to system not on the domain

Summary:
I was given a web server that is on a domain but need to back up files to another server (file server) that is not on the domain and with different credentials than the one I am logged on with (or the user assigned to the web server). I was given the credentials to use on the file server. The credential is also not on the domain. The assigned user for IIS was also a local user (ie not a domain user).

The code below was very simple to implement. I tried a few other solutions before finding this one. Others required knowing the domain. The key part for me was the CredentialCache and providing parameter for the machine I am trying to access.


Sample code from social.msdn.microsoft.com:
NetworkCredential theNetworkCredential = new NetworkCredential(username, password, domain);
CredentialCache theNetcache = new CredentialCache();
theNetCache.Add(@"\\computer", theNetworkCredential, "Basic", theNetworkCredential);
//then do whatever, such as getting a list of folders:
string[] theFolders = System.IO.Directory.GetDirectories("@\\computer\share");



No comments:

Post a Comment