0

This is a similar question on how to impersonate a logon.

However, I'm running into an issue when attempting to run System.IO.File.Copy() or System.IO.File.Move() while impersonating and receive the following error:

Logon failure: unknown user name or bad password

In my code, I've created a custom class to wrap the proper impersonate code with, so I can call it up like so:

using(var cnn = new {NetworkName}Connection()){
  // Work in the file system under admin privileges
  System.IO.File.Copy("{UNCSourcePath}", "{UNCTargetPath}", true);//Copy file from one server to another, overwrite if necessary
}

This way, I ensure the identity is properly disposed. My wrapper is posted below:

public class {NetworkName}Connection : IDisposable
  {
    [DllImport("advapi32.dll")]
    public static extern int LogonUser(String lpszUserName,String lpszDomain,String lpszPassword,int dwLogonType,int dwLogonProvider,ref IntPtr phToken);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool CloseHandle(IntPtr hObject);

    IntPtr tokenHandle;
    WindowsIdentity newId;
    public WindowsImpersonationContext User { get; set; }
    public {NetworkName}Connection()
    {
      this.tokenHandle = new IntPtr(0);
      if (LogonUser("{UserName}", "{NetworkName}", "{Password}", 9, 3, ref this.tokenHandle) != 0)
      {
        newId = new WindowsIdentity(tokenHandle);
        this.User = newId.Impersonate();
      }else{
        throw new Exception("Couldn't log onto {NetworkName}.");
      }
    }

    public void Dispose()
    {
      this.User.Dispose();
      CloseHandle(this.tokenHandle);
    }
  }

Within my wrapper, I'm able to successfully validate file existence and create FileInfo objects, but what could be the reason/fix for my application stopping on the Copy function?

Another important note would be that the server I'm connecting to is an old Windows Server 2000 machine. I also have similar code working in a VB.NET application, so I know the logic and credentials are correct.

tbm0115
  • 410
  • 11
  • 21
  • Either provide [MCVE] or ask someone around you to review and debug your code... There is no way for others to know why code you do not want to show works in some particular way. – Alexei Levenkov Sep 19 '17 at 20:08
  • @AlexeiLevenkov Are you asking for the wrapped code? Otherwise, I assume it would be a fundamental issue of calling those operations (Copy, Move) while impersonating or invalid LogonType/Provider. I'll go ahead and update to include the wrapped code as well. – tbm0115 Sep 19 '17 at 20:17
  • @AlexeiLevenkov Just added the wrapper class – tbm0115 Sep 19 '17 at 20:43

0 Answers0