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
个对象,但 我的应用程序停止复制功能的原因/修复是什么?
另一个重要的注意事项是我正在连接的服务器是旧的Windows Server 2000计算机。我也有类似的代码在VB.NET应用程序中工作,所以我知道逻辑和凭据是正确的。