This is a similar question关于如何模拟登录 .

但是,我在尝试模拟时运行 System.IO.File.Copy()System.IO.File.Move() 时遇到问题并收到以下错误:

登录失败:未知的用户名或密码错误

在我的代码中,我创建了一个自定义类来包装正确的模拟代码,所以我可以这样调用它:

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
}

这样,我确保身份得到妥善处理 . 我的包装发布在下面:

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);
    }
  }

在我的包装器中,我能够成功验证文件存在并创建 FileInfo 对象,但 what could be the reason/fix for my application stopping on the Copy function?

另一个重要的注意事项是我连接的服务器是旧的Windows Server 2000机器 . 我也有类似的代码在VB.NET应用程序中工作,所以我知道逻辑和凭据是正确的 .