sbornstein2
asked on
C# - Impersonate Context Question
I have a console application where I have to use impersonate to access a network directory. I then have code that loops though all the files in a directory on that network server. After a few minutes sometimes not all it throws a System.IO.Exception - the specified network path is no longer available. Any idea if this is possibly a impersonate issue and what I can change? Below is the code in an impersonate.cs class I have that I call first before running the code and here is the exact stack trace:
at System.IO.__Error.WinIOErr or(Int32 errorCode, String maybeFullPath)\r\n at System.IO.Directory.Intern alGetFileD irectoryNa mes(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)\r\n at System.IO.DirectoryInfo.Ge tFiles(Str ing searchPattern, SearchOption searchOption)\r\n at System.IO.DirectoryInfo.Ge tFiles(Str ing searchPattern)\r\n at BillRunPowerCleanup.Proram .CleanupMa cOldPDFs() in C:\\Applications\\BillRunP ower\\Bill RunPowerCl eanup\\Bil lRunPowerC leanup\\Pr ogram.cs:l ine 56"
at System.IO.__Error.WinIOErr
public class Impersonator
{
public WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")]
public extern static bool CloseHandle(IntPtr hToken);
public bool Impersonate(string userName, string domain, string password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
// request default security provider a logon token with LOGON32_LOGON_NEW_CREDENTIALS
// token returned is impersonation token, no need to duplicate
if(LogonUser(userName, domain, password, 9, 0, ref token) != 0)
{
tempWindowsIdentity = new WindowsIdentity(token);
impersonationContext = tempWindowsIdentity.Impersonate();
// close impersonation token, no longer needed
CloseHandle(token);
if (impersonationContext != null)
return true;
}
return false; // Failed to impersonate.
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.