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", "");

你可能感兴趣的:(C#)