views:

364

answers:

1

I have a .NET client app that intermittently loses connection to a UNC share where the user is either on a domain or has a local account with the same credentials on the server. Both SO and Google have plenty of examples using LogonUser and WNetAddConnection via P-Invoke, but both require the user's password. All our app needs to do is explicitly open a connection to a UNC, copy a file, and explicitly close the connection without providing credentials -- in other words, using the current credentials. Can anyone point me in the right direction on how to do that in C#?

+1  A: 

According to the documentation of the WNetAddConnection2 function, you can pass in Null for the user name to use the user context of the current process. I assume that means it will use the security context of the account running your client application. MSDN also says to pass in Null for the password to use the password associated with whatever user name is specified.

Maybe setting both to Null will just magically work.

Chris Tybur
Thanks for the answer, Chris. I found that part of the docs and actually tried that before you posted. It appears to work, as no error occurs when passing null, but I'm having a hard time proving that the connection is closed after calling WNetCancelConnection2. Is there something I should look for on the server?
flipdoubt
On the server, the only thing that comes to mind is to go into Computer Management and go to System Tools -> Shared Folders -> Open Sessions and see if there's evidence of the client connection to the given share. If the server is running Windows 2008 you can fire up the Share and Storage Management snap-in to see the same info. I assume a session will appear for the given user during the file copy, then disappear shortly after the call to WNetCancelConnection2. I always set the last parameter of that function to 1 to force a disconnect.
Chris Tybur