.Net 磁盘映射内网远程共享文件夹 电脑版发表于:2023/11/16 8:54 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.Net 磁盘映射内网远程共享文件夹 [TOC] ```csharp public class WNetHelper { public 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; } } ``` tn2>调用方式 ```csharp // 用户名 密码 远程路径 本地盘符 state = WNetHelper.WNetAddConnection(user, pwd, @"\\hznetapp1\hrs-cfa", "P:"); if (state.Equals(0)) { _logger.LogInformation($"创建驱动成功:{state} P:\\Jobs存在不? {Directory.Exists("P:\\Jobs")}"); //创建共享目录的上传路径 if (Directory.Exists("P:\\Jobs")) { _logger.LogInformation("创建驱动成功:" + state.ToString()); } } else { _logger.LogInformation("添加网络驱动器错误,错误号:" + state.ToString()); } ```