Reputation: 493
I have written a helper tool which performs various tasks. One of the tasks that it performs is to open a Windows explorer window locally, pointing to a PC on the network. Something like opening Windows Explorer manually and entering a network location in the path \\192.168.201.111\c$.
I have done this using the built in Process class:
var processInfo = new ProcessStartInfo
{
Arguments = GetFullPathCDRive(), /*This results in something like: \\192.168.202.179\c$*/
FileName = "explorer.exe",
UserName = Username,
Password = GetPasswordAsSecureString(),
Domain = Domain,
UseShellExecute = false,
};
Process.Start(processInfo);
This code works fine if I remove the Username and Password entry from the processinfo object (assuming i've already browsed to that network location and stored the username and password) but stops working if I add it. If I try and specify the Username and Password it throws an exception with the following error even though the Username and Password are correct:
{"Logon failure: unknown user name or bad password"}
Does anyone have any idea why I am getting this exception? Should I be attempting to achieve this differently, i.e. not using the built in C# Process class, perhaps using some underlying Windows Calls?
The GetPasswordAsSecureString function is as follows if it helps. I'm using this to pass in a password string and return me a SecureString, required by the ProcessStartInfo class:
public SecureString GetPasswordAsSecureString()
{
if (Password == null)
throw new ArgumentNullException("password");
var securePassword = new SecureString();
foreach (char c in Password)
securePassword.AppendChar(c);
securePassword.MakeReadOnly();
return securePassword;
}
Thanks in advance for any help or advice.
Regards
Upvotes: 1
Views: 1309
Reputation: 493
I couldn't find a way of passing the username and password when opening Windows Explorer but I wanted to post my solution that I went with in the end, in case it helps somebody else.
To solve this, I used the Credential Management library to add the credentials to the Windows Credential Manager before opening explorer. This has the same affect as exploring to the network path before hand and adding the credentials when prompted, asking Windows to remember them.
using CredentialManagement;
return new Credential
{
Target = target,
Type = CredentialType.DomainPassword,
PersistanceType = PersistanceType.Enterprise,
Username = string.Format("{0}\\{1}", NetworkManager.DOMAIN, username),
Password = password,
}.Save();
Thanks
Upvotes: 1