Bypass username/password dialog when accessing remote network

  • Thread starter Thread starter thoducng
  • Start date Start date
T

thoducng

I am writing some code to access share folder on a remote network.


DirectoryInfo dicInfo = new DirectoryInfo("remoteNetwork\shareFolder");



if (dicInfo.Exists)
{
//application code followed



}


The problem is when I ran this code, it always give me dicInfo.Exists =


false even though the directory did exists. If I go to Start\Run\ and
type in \\remoteNetWork\shareFolder, a dialog will pop up ask me for
username/password. After that if I run the code again and
dicInfo.Exists = true, which means the username/password has been
cached somewhere.


I also try to use WebRequest class but with no success:
System.Net.NetworkCredential myCredentials = new
System.Net.NetworkCredential("","","");
myCredentials.Domain = "";
myCredentials.UserName = "username";
myCredentials.Password = "password";
Uri myUrl=new Uri("file://remoteNetwork/shareFolder/New Text
Document.txt");
WebRequest myWebRequest = WebRequest.Create(myUrl);
Console.WriteLine("\n\nRequest to Url is sent.Waiting for
response...Please wait ...");
CredentialCache wrCache = new CredentialCache();
wrCache.Add(myUrl,"NTLM", myCredentials);
myWebRequest.Credentials = wrCache;
myWebRequest.PreAuthenticate = true;
wp.Credentials = wrCache;
WebResponse myWebResponse = myWebRequest.GetResponse();


The exception is thrown at the last line. It is either access is denied



or bad username or password. I also try to change "NTLM" to "Basic"
with no success. If I provide username, password in a dialog as the
above case, the code then work just fine. It means that the
NetworkCredential doesn't even need to do its work.
It is essential for my application to provide username/password behind
the scene because user is not always there to provide it. Any help/
guidance is appreciated.
 
The general answer to this is to use WNetAddConnection2, connecting to the
generic share \\server\IPC$ . Don't think there's an equivalent in the
framework, that's a P/Invoke.

Assuming that you actually know username and password, you first connect
without specifying them because the user might already be connected to the
system (and possibly with a different set of credentials) and you'll get an
ERROR_ALREADY_ASSIGNED result. If the user is not connected, call it again
this time passing the username and password. It's good form to call
WNetCancelConnection when you're through.

Normally you'd call WNetAddConnection2 with CONNECT_INTERACTIVE |
CONNECT_PROMPT as the final parameter, so Windows would prompt the user for
credentials, however you either already know them or the user in't there if
I understand you correctly.
 
Back
Top