using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public int dwScope;
public int dwType;
public int dwDisplayType;
public int dwUsage;
public string LocalName;
public string RemoteName;
public string Comment;
public string provider;
}
[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WNetGetConnection(
[MarshalAs(UnmanagedType.LPTStr)] string localName,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
ref int length); [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flag);
[DllImport("mpr.dll", CharSet = CharSet.Ansi)]
private static extern int WNetCancelConnection2(string lpname, int flag, bool force); /// <summary>
/// 映射网络驱动器
/// </summary>
/// <param name="localName">本地盘符 如U:</param>
/// <param name="remotePath">远程路经 如\\\\172.18.118.106\\f</param>
/// <param name="userName">远程服务器用户名</param>
/// <param name="password">远程服务器密码</param>
/// <returns>true映射成功,false映射失败</returns>
public static bool WNetReflectDrive(string localName, string remotePath, string userName, string password)
{
NetResource netResource = new NetResource();
netResource.dwScope = ;
netResource.dwType = 0x1;
netResource.dwDisplayType = ;
netResource.dwUsage = ;
netResource.LocalName = localName;
netResource.RemoteName = remotePath;
netResource.provider = null;
int ret = WNetAddConnection2(netResource, password, userName, );
if (ret == )
return true;
return false;
}
使用方法:
Program.WNetReflectDrive("z:", @"\\192.168.0.1\XXXX", "admin", "");