这是关于如何模拟登录的类似问题。
但是,我在尝试运行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 应用程序中也有类似的代码,所以我知道逻辑和凭据是正确的。