Link to home
Start Free TrialLog in
Avatar of sbornstein2
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.WinIOError(Int32 errorCode, String maybeFullPath)\r\n   at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)\r\n   at System.IO.DirectoryInfo.GetFiles(String searchPattern, SearchOption searchOption)\r\n   at System.IO.DirectoryInfo.GetFiles(String searchPattern)\r\n   at BillRunPowerCleanup.Proram.CleanupMacOldPDFs() in C:\\Applications\\BillRunPower\\BillRunPowerCleanup\\BillRunPowerCleanup\\Program.cs:line 56"
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.
        }
 
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaylanreilor
kaylanreilor
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial