您的位置:首页 > 其它

带用户名密码---远程访问另一台主机中共享文件夹中文件

2008-09-01 17:15 806 查看
using System.Runtime.InteropServices;
using System;
using System.ComponentModel;
using System.IO;
enum LogonType : uint
{

Interactive = 2,

Network = 3,

Batch = 4,

Service = 5,

Unlock = 7,

NetworkClearText = 8,

NewCredentials = 9
}
enum LogonProvider : uint
{

Default = 0,

WinNT35 = 1,

WinNT40 = 2,

WinNT50 = 3,
}
class IdentityScope : IDisposable
{
[DllImport("Advapi32.dll")]
static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword,
LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken);
[DllImport("Advapi32.DLL")]
static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.DLL")]
static extern bool RevertToSelf();
[DllImport("Kernel32.dll")]
static extern int GetLastError();

bool disposed;

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 Win32Exception(errorCode);
}
}

~IdentityScope()
{
Dispose(false);
}

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Nothing to do.
}
RevertToSelf();
disposed = true;
}
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

public class test
{
//下面是一个测试函数:
public static void aaa()
{
using (new IdentityScope(@"10.0.0.68", "aaa", "qwert", LogonType.NewCredentials, LogonProvider.WinNT50))
{
File.Copy("////10.0.0.68//autotxt//2008-3-24 17.22.28.txt", @"C:/rere.txt");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐