C#映射网络驱动器(WinAPI)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#映射⽹络驱动器(WinAPI)
1//资源类,⽤于记录映射类型和设置
2 [StructLayout(LayoutKind.Sequential)]
3publicclass NETRESOURCE
4 {
5publicint dwScope;//只能取2
6publicint dwType;//0为打印机或驱动器,1为驱动器,2为打印机
7publicint dwDisplayType;//取0,⾃动设置
8publicint dwUsage;//取1
9publicstring LocalName;//本地盘符或名称
10publicstring RemoteName;//远程地址
11publicstring Comment;//NULL即可,A pointer to a NULL-terminated string that contains a comment supplied by the network provider. 12publicstring Provider;//NULL即可,A pointer to a NULL-terminated string that contains the name of the provider that owns the resource. This member can be NULL if the provider name is unknown.
13 }
14
15//控制(主)类,创建、删除映射
16publicclass NetDriveCtl
17 {
18 ArrayList NDList;
19
20public NetDriveCtl()
21 {
22 NDList =new ArrayList();
23 }
24
25publicstring CreateDrive(string LocalName, string RemoteName,string UserName,string Password)
26 {
27 NETRESOURCE NetDrive =new NETRESOURCE();
28 NetDrive.dwScope =2;
29 NetDrive.dwType =0;
30 NetDrive.dwDisplayType =0;
31 NetDrive.dwUsage =1;
32 NetDrive.LocalName = LocalName;
33 NetDrive.RemoteName = RemoteName;
34
35 NDList.Add(NetDrive);
36return ConnectDrive(NetDrive, UserName, Password);
37 }
38
39public Boolean DeleteDrive(string LocalName, string RemoteName)
40 {
41foreach (NETRESOURCE NetDrive in NDList)
42 {
43if ((NetDrive.LocalName == LocalName) && (NetDrive.RemoteName == RemoteName))
44 {
45 DisconnectDrive(NetDrive);
46 NDList.Remove(NetDrive);
47returntrue;
48 }
49 }
50returnfalse;
51 }
52
53privatestring ConnectDrive(NETRESOURCE NetDrive, string UserName, string Password)
54 {
55 StringBuilder UN =new StringBuilder(UserName);
56 StringBuilder PW =new StringBuilder(Password);
57
58return WNetAddConnection2(NetDrive, PW, UN, 0).ToString();
59 }
60
61privatestring DisconnectDrive(NETRESOURCE NetDrive)
62 {
63string LocalName = NetDrive.LocalName;
64return WNetCancelConnection2(LocalName, 1, true).ToString();
65 }
66
67privatestring DisconnectDrive(string LocalName)
68 {
69return WNetCancelConnection2(LocalName, 1, true).ToString();
70 }
71
72//这两个是系统API函数
73 [DllImport("mpr.dll", EntryPoint ="WNetAddConnection2")]
74privatestaticexternuint WNetAddConnection2([In] NETRESOURCE lpNetResource, StringBuilder lpPassword, StringBuilder lpUsername, uint dwFlags);
75 [DllImport("Mpr.dll")]
76privatestaticexternuint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);
77 }
调⽤⽰例:
NetDriveCtl ndc =new NetDriveCtl();
ndc.CreateDrive("T:", @"\\1.1.1.1\V$","密码","⽤户名");
ndc.CreateDrive("T:", @"\\1.1.1.1\V$","密码","⽤户名");。

相关文档
最新文档