MyBox

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

1 //资源类,用于记录映射类型和设置
2   [StructLayout(LayoutKind.Sequential)]
3 publicclass NETRESOURCE
4 {
5 publicint dwScope;//只能取2
6  publicint dwType;//0为打印机或驱动器,1为驱动器,2为打印机
7  publicint dwDisplayType;//取0,自动设置
8  publicint dwUsage;//取1
9 publicstring LocalName;//本地盘符或名称
10 publicstring RemoteName;//远程地址
11 publicstring Comment;//NULL即可,A pointer to a NULL-terminated string that contains a comment supplied by the network provider.
12 publicstring 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 //控制(主)类,创建、删除映射
16 publicclass NetDriveCtl
17 {
18 ArrayList NDList;
19
20 public NetDriveCtl()
21 {
22 NDList =new ArrayList();
23 }
24
25 publicstring 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);
36 return ConnectDrive(NetDrive, UserName, Password);
37 }
38
39 public Boolean DeleteDrive(string LocalName, string RemoteName)
40 {
41 foreach (NETRESOURCE NetDrive in NDList)
42 {
43 if ((NetDrive.LocalName == LocalName) && (NetDrive.RemoteName == RemoteName))
44 {
45 DisconnectDrive(NetDrive);
46 NDList.Remove(NetDrive);
47 returntrue;
48 }
49 }
50 returnfalse;
51 }
52
53 privatestring ConnectDrive(NETRESOURCE NetDrive, string UserName, string Password)
54 {
55 StringBuilder UN =new StringBuilder(UserName);
56 StringBuilder PW =new StringBuilder(Password);
57
58 return WNetAddConnection2(NetDrive, PW, UN, 0).ToString();
59 }
60
61 privatestring DisconnectDrive(NETRESOURCE NetDrive)
62 {
63 string LocalName = NetDrive.LocalName;
64 return WNetCancelConnection2(LocalName, 1, true).ToString();
65 }
66
67 privatestring DisconnectDrive(string LocalName)
68 {
69 return WNetCancelConnection2(LocalName, 1, true).ToString();
70 }
71
72 //这两个是系统API函数
73 [DllImport("mpr.dll", EntryPoint ="WNetAddConnection2")]
74 privatestaticexternuint WNetAddConnection2([In] NETRESOURCE lpNetResource, StringBuilder lpPassword, StringBuilder lpUsername, uint dwFlags);
75 [DllImport("Mpr.dll")]
76 privatestaticexternuint 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$","密码","用户名");

 

posted on 2010-12-29 17:31  MyBox  阅读(2049)  评论(0编辑  收藏  举报