Hello all,
Here is my problem. I have a windows service (C#) that is
supposed to move files from/to the local drive to/from a
UNC share (\\domainserver \share). The service is running
on a Win3k server not connected to a domain, as a local
user. The service impersonates a local user (on
domainserver) that has full permissions to that share. Any
File.Move, File.Copy operations are successfull. Any
Directory.GetFi les fail with "Logon failure: unknown user
name or bad password", stack trace is Exception stack
trace: at System.IO.__Err or.WinIOError(I nt32 errorCode,
String str) at
System.IO.Direc tory.InternalGe tFileDirectoryN ames(String
fullPath, String userPath, Boolean file) at
System.IO.Direc tory.InternalGe tFiles(String path, String
userPath, String searchPattern) at
System.IO.Direc tory.GetFiles(S tring path, String
searchPattern). The call succeeds if I run the service
under a local account with the same user name/pwd or if
the server is connected to the domain and the service runs
as any domain account.
The impersonation code is similar with the samples from
MSDN (sorry about the formatting):
public static void ImpersonateUser (string domainName,
string userName, string password)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr
(0);
try
{
// Get the user token for
the specified user, domain, and password using the
// unmanaged LogonUser
method.
const int
SecurityImperso nation = 2;
tokenHandle = IntPtr.Zero;
dupeTokenHandle =
IntPtr.Zero;
// Call LogonUser to
obtain a handle to an access token.
bool returnValue =
LogonUser(userN ame, domainName, password,
(int)
LogonType.LOGON 32_LOGON_NEW_CR EDENTIALS, (int)
LogonProvider.L OGON32_PROVIDER _DEFAULT, ref
tokenHandle);
if (false == returnValue)
{
int ret =
Marshal.GetLast Win32Error();
throw new
System.Componen tModel.Win32Exc eption(ret, GetErrorMessage
(ret));
}
//Duplicate the token
bool retVal =
DuplicateToken( tokenHandle, SecurityImperso nation, ref
dupeTokenHandle );
if (false == retVal)
{
CloseHandle
(tokenHandle);
throw new
ApplicationExce ption("Exceptio n thrown in trying to
duplicate token.");
}
// The token that is
passed to the following constructor must
// be a primary token in
order to use it for impersonation.
WindowsIdentity newId =
new WindowsIdentity (dupeTokenHandl e);
WindowsImperson ationContext impersonatedUse r =
newId.Impersona te();
try
{
do stuff;
}
catch {}
// Stop impersonating the
user.
impersonatedUse r.Undo();
// Free the tokens.
if (tokenHandle !=
IntPtr.Zero)
CloseHandle
(tokenHandle);
if (dupeTokenHandl e !=
IntPtr.Zero)
CloseHandle
(dupeTokenHandl e);
}
catch(Exception ex)
{
throw ex;
}
}
}
Thanks a lot for any help or ideas,
Chris