using System.Runtime.InteropServices; namespace Edu.Common.Plugin { /// /// 网络资源访问帮助类 /// public class NetFileHelper { [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 { /// /// 下述常数之一 /// 1、枚举连接的资源 /// 2、枚举所有资源 /// 3、枚举永久性连接 /// public int dwScope; /// /// 下述常数之一 /// 1、 枚举所有资源 /// 2、 枚举磁盘 /// 3、枚举打印机 /// public int dwType; /// /// 带有前缀RESOURCEDISPLAYTYPE的一个常数,对资源的类型进行了定义(在网络浏览器中如何显示) /// public int dwDisplayType; /// /// 下述标志的一个或多个 /// 1、可同这个资源连接 /// 2、这个资源包含了可以枚举的额外资源 /// public int dwUsage; /// /// 由本地系统引用的资源名称。只能用于已连接的资源 /// public string lpLocalName; /// /// 资源的网络名 /// public string lpRemoteName; /// /// 由网络供应商设置 /// public string lpComment; /// /// 网络供应商的名字 /// public string lpProvider; } /// /// 为网络共享做本地映射 /// /// 访问用户名(windows系统需要加计算机名,如:comp-1\user-1) /// 访问用户密码 /// 网络共享路径(如:\\192.168.0.9\share) /// 本地映射盘符 /// public static uint WNetAddConnection(string username, string password, string remoteName, string localName) { NetResource netResource = new NetResource { dwScope = 2, dwType = 1, dwDisplayType = 3, dwUsage = 1, lpLocalName = localName, 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; } } }