这里直接讲解决方法,至于为什么这样做,原理是什么,只能你们自己去研究了,因为我也不知道 QAQ。
1.IIS服务器要有一个和映射盘服务器一样的账号,例如映射盘账号为administrator,密码为123456,那么你IIS服务器也要有一个一模一样的账号。
2.切换IIS账号类
因为IIS默认账号无法连接映射盘。
public class LogonImpersonate : IDisposable
{
static public string DefaultDomain
{
get
{
return ".";
}
}
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_PROVIDER_DEFAULT = 0;
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
extern static bool CloseHandle(IntPtr handle);
[System.Runtime.InteropServices.DllImport("Advapi32.dll", SetLastError = true)]
extern static bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken
);
IntPtr token;
System.Security.Principal.WindowsImpersonationContext context;
public LogonImpersonate(string username, string password)
{
if (username.IndexOf("\\") == -1)
{
Init(username, password, DefaultDomain);
}
else
{
string[] pair = username.Split(new char[] { '\\' }, 2);
Init(pair[1], password, pair[0]);
}
}
public LogonImpersonate(string username, string password, string domain)
{
Init(username, password, domain);
}
void Init(string username, string password, string domain)
{
if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
{
bool error = true;
try
{
context = System.Security.Principal.WindowsIdentity.Impersonate(token);
error = false;
}
finally
{
if (error)
CloseHandle(token);
}
}
else
{
int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
IntPtr tempptr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempptr, err, 0, ref msg, 255, ref tempptr);
throw (new Exception(msg));
}
}
~LogonImpersonate()
{
Dispose();
}
public void Dispose()
{
if (context != null)
{
try
{
context.Undo();
}
finally
{
CloseHandle(token);
context = null;
}
}
}
}
3.连接映射盘类
public class WNetHelper
{
[DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]
private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
[DllImport("mpr.dll", EntryPoint = "WNetCancelConnection2")]
private static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public int dwScope;
public int dwType;
public int dwDisplayType;
public int dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
/// <summary>
/// 为网络共享做本地映射
/// </summary>
/// <param name="username">访问用户名(windows系统需要加计算机名,如:comp-1\user-1)</param>
/// <param name="password">访问用户密码</param>
/// <param name="remoteName">网络共享路径(如:\\192.168.0.9\share)</param>
/// <param name="localName">本地映射盘符</param>
/// <returns></returns>
public static uint WNetAddConnection(string username, string password, string remoteName, string localName)
{
NetResource netResource = new NetResource();
netResource.dwScope = 2;
netResource.dwType = 1;
netResource.dwDisplayType = 3;
netResource.dwUsage = 1;
netResource.lpLocalName = localName;
netResource.lpRemoteName = remoteName.TrimEnd('\\');
uint result = WNetAddConnection2(netResource, password, username, 0);
return result;
}
public static uint WNetCancelConnection(string name, uint flags, bool force)
{
uint nret = WNetCancelConnection2(name, flags, force);
return nret;
}
}
4.测试
映射完之后,你就可以直接使用你映射的盘符来访问里面的文件。
public void getFile()
{
//切换IIS账号
LogonImpersonate imper = new LogonImpersonate("administrator", "123456");
//连接映射盘
WNetHelper.WNetAddConnection(@"administrator", "123456", @"\\192.168.16.999\test", "Z:");
//读取映射盘中filedir文件下所有的文件
DirectoryInfo di = new DirectoryInfo(@"Z:\filedir");
}
我使用时遇到的问题点:
1.如果是在本机测试时,不要把切换IIS账号那一步代码加上,否则连接映射盘时会一直返回状态为1222。
2.你要看在你本机连接映射盘时输入的账号有没有加计算机名,如果有加,那么在连接映射盘那一步你就要加上计算机名,你可以改成 WNetHelper.WNetAddConnection(@"计算机名\administrator", "123456", @"\\192.168.16.999\test", "Z:")。
3.不管是切换IIS账号的步骤,还是连接映射盘的步骤,输入的账号是区分大小写的。我在切换IIS账号这一步骤时,把administrator写成Administrator,结果就报错了。