tags:

views:

24

answers:

2
A: 

You don't need impersonation all you have to do is to establish a file mapping using the credentials you want to use. You can accomplish this using either net use as a shell out command or WNetAddConnection2

rerun
A: 

If you are running as a service, you may need to impersonate. This is not the complete code but the gist of it:

     [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern unsafe int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref string lpBuffer, int nSize, IntPtr* arguments);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool CloseHandle(IntPtr handle);


IntPtr token = IntPtr.Zero;

            bool isSuccess = LogonUser(username, domain, password, impersonationType, Logon32ProviderDefault, ref token);
            if (!isSuccess)
            {
                RaiseLastError();
            }

            WindowsIdentity newIdentity = new WindowsIdentity(token);
            WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();

Save the token and then later

CloseHandle(token);
Otávio Décio
If it is a windows service you can run it under required user account. Or create a special account for this service.
Den
@Den Yes you can. Which does not prevent me from offering an alternative.
Otávio Décio