Is there some way to authenticate as a local (not network) user in order to copy files over the network in .Net?
net use
is not an option, and I can't seem to get LogonUser to work.
Any ideas?
[Edit] Here is some code:
public class UserImpersonator : IDisposable
{
private WindowsImpersonationContext _impersonationContext;
private IntPtr _userHandle = IntPtr.Zero;
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hHandle);
public UserImpersonator(string username, string password)
{
LogonUser(username, "", password, (int)LogonType.LOGON32_LOGON_NETWORK,
(int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out _userHandle);
_impersonationContext = WindowsIdentity.Impersonate(_userHandle);
}
public void Dispose()
{
CloseHandle(_userHandle);
_impersonationContext.Undo();
}
private enum LogonType : int
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
private enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
}
}
When I wrap the File.Copy
operation in using(new UserImpersonator(username, password))
, I get:
System.IO.IOException: Logon failure: unknown user name or bad password.
If, however, I first try to connect to the share in explorer (entering the authentication info when it asks for it), the File.Copy
works. It appears that the above code doesn't do anything at all.