C#映射网络驱动器

using System.Runtime.InteropServices;

 

 1 [StructLayout(LayoutKind.Sequential)]
 2         public class NetResource
 3         {
 4             public int dwScope;
 5             public int dwType;
 6             public int dwDisplayType;
 7             public int dwUsage;
 8             public string LocalName;
 9             public string RemoteName;
10             public string Comment;
11             public string provider;
12         }
13         [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
14         public static extern int WNetGetConnection(
15             [MarshalAs(UnmanagedType.LPTStr)] string localName,
16             [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
17             ref int length);
18 
19         [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
20         private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flag);
21         [DllImport("mpr.dll", CharSet = CharSet.Ansi)]
22         private static extern int WNetCancelConnection2(string lpname, int flag, bool force);
23 
24         /// <summary>
25         /// 映射网络驱动器
26         /// </summary>
27         /// <param name="localName">本地盘符 如U:</param>
28         /// <param name="remotePath">远程路经 如\\\\172.18.118.106\\f</param>
29         /// <param name="userName">远程服务器用户名</param>
30         /// <param name="password">远程服务器密码</param>
31         /// <returns>true映射成功,false映射失败</returns>
32         public static bool WNetReflectDrive(string localName, string remotePath, string userName, string password)
33         {
34             NetResource netResource = new NetResource();
35             netResource.dwScope = 2;
36             netResource.dwType = 0x1;
37             netResource.dwDisplayType = 3;
38             netResource.dwUsage = 1;
39             netResource.LocalName = localName;
40             netResource.RemoteName = remotePath;
41             netResource.provider = null;
42             int ret = WNetAddConnection2(netResource, password, userName, 0);
43             if (ret == 0)
44                 return true;
45             return false;
46         }

 

 

使用方法:

Program.WNetReflectDrive("z:", @"\\192.168.0.1\XXXX", "admin", "");

转载于:https://www.cnblogs.com/xxxteam/p/3316553.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值