using System.Runtime.InteropServices; //添加引用
//引用系統win32 Api
//http://msdn.microsoft.com/zh-cn/library/aa378184(v=VS.85)
public class IdentityScope : IDisposable
{
private bool disposed;
[DllImport("Advapi32.dll")]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
[DllImport("Advapi32.DLL")]
private static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.DLL")]
private static extern bool RevertToSelf();
[DllImport("Kernel32.dll")]
private static extern int GetLastError();
public IdentityScope(string domain, string userName, string password)
: this(domain, userName, password, LogonType.Interactive, LogonProvider.Default)
{
}
public IdentityScope(string domain, string userName, string password, LogonType logonType, LogonProvider logonProvider)
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(domain))
domain = ".";
IntPtr token;
int errorCode = 0;
if (LogonUser(userName, domain, password, logonType, logonProvider, out token))
{
if (!ImpersonateLoggedOnUser(token))
errorCode = GetLastError();
}
else
errorCode = GetLastError();
if (errorCode != 0)
throw new System.ComponentModel.Win32Exception(errorCode);
}
~IdentityScope()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
}
RevertToSelf();
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
public enum LogonType : uint
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkClearText = 8,
NewCredentials = 9
}
public enum LogonProvider : uint
{
Default = 0,
WinNT35 = 1,
WinNT40 = 2,
WinNT50 = 3,
}
public enum ProcessCode : uint
{
Result = 1,
Success = 2,
Failure = 4
}
public class Program
{
static void Main()
{
try
{
string IpAddr = "192.168.1.23";
string souceFileName = "D:\\abc.txt";
string targetFileName = "\\192.168.1.23\\D$\\abc.txt";
string UserName = "Administrator";
string Password = "123456";
//信令拷beike
using (new IdentityScope(IpAddr
, UserName
, Password
, LogonType.NewCredentials
, LogonProvider.WinNT50))
{
System.IO.File.Copy(souceFileName, targetFileName, true);
}
}
catch (Exception e)
{
}
}
}
更多信息參見:http://msdn.microsoft.com/zh-cn/library/aa378184(v=VS.85)