NetworkConnection.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. namespace LYFZ.Network
  7. {
  8. #region 网络资源相关枚举
  9. /// <summary>
  10. /// 连接错误ID
  11. /// </summary>
  12. public enum ERROR_ID
  13. {
  14. /// <summary>
  15. /// 成功
  16. /// </summary>
  17. ERROR_SUCCESS = 0, // Success
  18. ERROR_BUSY = 170,
  19. ERROR_MORE_DATA = 234,
  20. ERROR_NO_BROWSER_SERVERS_FOUND = 6118,
  21. ERROR_INVALID_LEVEL = 124,
  22. ERROR_ACCESS_DENIED = 5,
  23. ERROR_INVALID_PASSWORD = 86,
  24. ERROR_INVALID_PARAMETER = 87,
  25. ERROR_BAD_DEV_TYPE = 66,
  26. ERROR_NOT_ENOUGH_MEMORY = 8,
  27. ERROR_NETWORK_BUSY = 54,
  28. ERROR_BAD_NETPATH = 53,
  29. ERROR_NO_NETWORK = 1222,
  30. ERROR_INVALID_HANDLE_STATE = 1609,
  31. ERROR_EXTENDED_ERROR = 1208,
  32. ERROR_DEVICE_ALREADY_REMEMBERED = 1202,
  33. ERROR_NO_NET_OR_BAD_PATH = 1203
  34. }
  35. /// <summary>
  36. /// 资源范围
  37. /// </summary>
  38. public enum RESOURCE_SCOPE
  39. {
  40. RESOURCE_CONNECTED = 1,
  41. RESOURCE_GLOBALNET = 2,
  42. RESOURCE_REMEMBERED = 3,
  43. RESOURCE_RECENT = 4,
  44. RESOURCE_CONTEXT = 5
  45. }
  46. /// <summary>
  47. /// 资源类型
  48. /// </summary>
  49. public enum RESOURCE_TYPE
  50. {
  51. RESOURCETYPE_ANY = 0,
  52. RESOURCETYPE_DISK = 1,
  53. RESOURCETYPE_PRINT = 2,
  54. RESOURCETYPE_RESERVED = 8,
  55. }
  56. /// <summary>
  57. /// 资源用法
  58. /// </summary>
  59. public enum RESOURCE_USAGE
  60. {
  61. RESOURCEUSAGE_CONNECTABLE = 1,
  62. RESOURCEUSAGE_CONTAINER = 2,
  63. RESOURCEUSAGE_NOLOCALDEVICE = 4,
  64. RESOURCEUSAGE_SIBLING = 8,
  65. RESOURCEUSAGE_ATTACHED = 16,
  66. RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
  67. }
  68. /// <summary>
  69. /// 资源显示类型
  70. /// </summary>
  71. public enum RESOURCE_DISPLAYTYPE
  72. {
  73. RESOURCEDISPLAYTYPE_GENERIC = 0,
  74. RESOURCEDISPLAYTYPE_DOMAIN = 1,
  75. RESOURCEDISPLAYTYPE_SERVER = 2,
  76. RESOURCEDISPLAYTYPE_SHARE = 3,
  77. RESOURCEDISPLAYTYPE_FILE = 4,
  78. RESOURCEDISPLAYTYPE_GROUP = 5,
  79. RESOURCEDISPLAYTYPE_NETWORK = 6,
  80. RESOURCEDISPLAYTYPE_ROOT = 7,
  81. RESOURCEDISPLAYTYPE_SHAREADMIN = 8,
  82. RESOURCEDISPLAYTYPE_DIRECTORY = 9,
  83. RESOURCEDISPLAYTYPE_TREE = 10,
  84. RESOURCEDISPLAYTYPE_NDSCONTAINER = 11
  85. }
  86. #endregion
  87. /// <summary>
  88. /// 网络连接
  89. /// </summary>
  90. public class NetworkConnection
  91. {
  92. /// <summary>
  93. /// NET资源结构
  94. /// </summary>
  95. [StructLayout(LayoutKind.Sequential)]
  96. public struct NETRESOURCE
  97. {
  98. public RESOURCE_SCOPE dwScope;
  99. public RESOURCE_TYPE dwType;
  100. public RESOURCE_DISPLAYTYPE dwDisplayType;
  101. public RESOURCE_USAGE dwUsage;
  102. [MarshalAs(UnmanagedType.LPStr)]
  103. public string lpLocalName;
  104. [MarshalAs(UnmanagedType.LPStr)]
  105. public string lpRemoteName;
  106. [MarshalAs(UnmanagedType.LPStr)]
  107. public string lpComment;
  108. [MarshalAs(UnmanagedType.LPStr)]
  109. public string lpProvider;
  110. }
  111. [DllImport("mpr.dll")]
  112. public static extern int WNetAddConnection2A(NETRESOURCE[] lpNetResource, string lpPassword, string lpUserName, int dwFlags);
  113. [DllImport("mpr.dll")]
  114. public static extern int WNetCancelConnection2A(string sharename, int dwFlags, int fForce);
  115. /// <summary>
  116. /// 获取一个未被占用的驱动盘符号
  117. /// </summary>
  118. /// <returns></returns>
  119. public static string GetDriveLetter()
  120. {
  121. System.IO.DriveInfo[] drivers = System.IO.DriveInfo.GetDrives();
  122. string[] Letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
  123. string tempLetter = "";
  124. foreach (System.IO.DriveInfo disk in drivers)//逐个显示到树形目录或者文件列表中
  125. {
  126. tempLetter += disk.Name;
  127. }
  128. string Letter =null;
  129. for (int i = 4; i < Letters.Length; i++)
  130. {
  131. Letter = Letters[i];
  132. if (!tempLetter.ToLower().Contains(Letter.ToLower()))
  133. {
  134. Letter = Letter + ":";
  135. break;
  136. }
  137. else {
  138. Letter = null;
  139. }
  140. }
  141. return Letter;
  142. }
  143. /// <summary>
  144. /// 获取一个未被占用的驱动盘符号
  145. /// </summary>
  146. /// <returns></returns>
  147. public static string GetStaticDriveLetter()
  148. {
  149. return GetDriveLetter();
  150. }
  151. /// <summary>
  152. /// 连接网络共享资源
  153. /// </summary>
  154. /// <param name="remotePath">运程地址</param>
  155. /// <param name="username">用户名</param>
  156. /// <param name="password">密码</param>
  157. /// <param name="localPath">连接后的映射盘符,可以为空 如:“X:”</param>
  158. /// <returns></returns>
  159. public static int Connect(string remotePath, string username, string password, string localPath=null)
  160. {
  161. NETRESOURCE[] share_driver = new NETRESOURCE[1];
  162. share_driver[0].dwScope = RESOURCE_SCOPE.RESOURCE_GLOBALNET;
  163. share_driver[0].dwType = RESOURCE_TYPE.RESOURCETYPE_DISK;
  164. share_driver[0].dwDisplayType = RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_SHARE;
  165. share_driver[0].dwUsage = RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE;
  166. /* if (localPath != null)
  167. {
  168. share_driver[0].lpLocalName = localPath;
  169. }
  170. else {
  171. localPath = GetDriveLetter();
  172. if (localPath != null)
  173. {
  174. share_driver[0].lpLocalName = localPath;
  175. }
  176. }
  177. */
  178. share_driver[0].lpRemoteName = remotePath;
  179. // if (localPath != null)
  180. // Disconnect(localPath);
  181. int ret = WNetAddConnection2A(share_driver, password, username, 1);
  182. return ret;
  183. }
  184. /// <summary>
  185. /// 连接网络共享资源
  186. /// </summary>
  187. /// <param name="remotePath">运程地址</param>
  188. /// <param name="username">用户名</param>
  189. /// <param name="password">密码</param>
  190. /// <param name="localPath">连接后的映射盘符,可以为空 如:“X:”</param>
  191. /// <returns></returns>
  192. public static int StaticConnect(string remotePath, string username, string password, string localPath = null)
  193. {
  194. return Connect(remotePath, username, password, localPath);
  195. }
  196. /// <summary>
  197. /// 断开映射连接
  198. /// </summary>
  199. /// <param name="localpath">映射盘符</param>
  200. /// <returns></returns>
  201. public static int StaticDisconnect(string localpath=null)
  202. {
  203. return Disconnect(localpath);
  204. }
  205. /// <summary>
  206. /// 断开映射连接
  207. /// </summary>
  208. /// <param name="localpath">映射盘符</param>
  209. /// <returns></returns>
  210. public static int Disconnect(string localpath = null)
  211. {
  212. return WNetCancelConnection2A(localpath, 0, 1);
  213. }
  214. /// <summary>
  215. /// 断开所有网络资源连接
  216. /// </summary>
  217. /// <returns></returns>
  218. public static string Disconnect()
  219. {
  220. return StaticExecuteCmd("net use * /del /y");
  221. }
  222. /// <summary>
  223. /// 断开所有网络资源连接
  224. /// </summary>
  225. /// <returns></returns>
  226. public static string StaticDisconnect()
  227. {
  228. return Disconnect();
  229. }
  230. /// <summary>
  231. /// 断开指定远程路径的网络资源连接
  232. /// </summary>
  233. /// <param name="remotePath">指定远程路径(如果连接时有映射device name 设备名,请输入映射device name 如:“X:”)</param>
  234. /// <returns></returns>
  235. public static string DisconnectRemotePath(string remotePath)
  236. {
  237. return StaticExecuteCmd("net use " + remotePath + " /del /y");
  238. }
  239. /// <summary>
  240. /// net use 命令连接网络共享资源
  241. /// </summary>
  242. /// <param name="remotePath">运程地址</param>
  243. /// <param name="userName">用户名</param>
  244. /// <param name="Pwd">密码</param>
  245. /// <param name="localPath">连接后的映射盘符,可以为空 如:“X:”也可以是 “*”表示所以可用设备名</param>
  246. /// <returns></returns>
  247. public static string ComdConnect(string remotePath, string userName="", string Pwd="", string localPath=null)
  248. {
  249. return StaticExecuteCmd(GetConnectSharedComdStr(remotePath, userName, Pwd, localPath));
  250. }
  251. /// <summary>
  252. /// 获取连接共享命令
  253. /// </summary>
  254. /// <param name="remotePath">运程地址</param>
  255. /// <param name="userName">用户名</param>
  256. /// <param name="Pwd">密码</param>
  257. /// <param name="localPath">连接后的映射盘符,可以为空 如:“X:”也可以是 “*”表示所以可用设备名</param>
  258. /// <returns></returns>
  259. public static string GetConnectSharedComdStr(string remotePath, string userName = "", string Pwd = "", string localPath = null)
  260. {
  261. if (localPath == null)
  262. {
  263. localPath = "";
  264. }
  265. return ("net use " + localPath + " " + remotePath + " \"" + Pwd + "\" /user:\"" + userName + "\"");
  266. }
  267. /// <summary>
  268. /// net use 命令连接网络共享资源
  269. /// </summary>
  270. /// <param name="remotePath">运程地址</param>
  271. /// <param name="userName">用户名</param>
  272. /// <param name="Pwd">密码</param>
  273. /// <param name="localPath">连接后的映射盘符,可以为空 如:“X:”也可以是 “*”表示所以可用设备名</param>
  274. /// <returns></returns>
  275. public static string StaticComdConnect(string remotePath, string userName, string Pwd, string localPath = null) {
  276. return ComdConnect(remotePath, userName, Pwd, localPath);
  277. }
  278. /// <summary>
  279. /// 断开指定远程路径的网络资源连接
  280. /// </summary>
  281. /// <param name="remotePath">指定远程路径</param>
  282. /// <returns></returns>
  283. public static string StaticDisconnectRemotePath(string remotePath)
  284. {
  285. return DisconnectRemotePath(remotePath);
  286. }
  287. /// <summary>
  288. /// 执行CMD命令
  289. /// </summary>
  290. /// <param name="command">CMD命令字符串</param>
  291. /// <returns></returns>
  292. public static string StaticExecuteCmd(string command) {
  293. return ExecuteCmd(command);
  294. }
  295. /// <summary>
  296. /// 执行CMD命令
  297. /// </summary>
  298. /// <param name="command">CMD命令字符串</param>
  299. /// <returns></returns>
  300. public static string ExecuteCmd(string command)
  301. {
  302. try
  303. {
  304. string str = command;
  305. System.Diagnostics.Process p = new System.Diagnostics.Process();
  306. p.StartInfo.FileName = "cmd.exe";
  307. p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
  308. p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
  309. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  310. p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
  311. p.StartInfo.CreateNoWindow = true;//不显示程序窗口
  312. // p.StartInfo.WorkingDirectory = System.Environment.GetEnvironmentVariable("windir")+"\\system32\\";
  313. p.Start();//启动程序
  314. //向cmd窗口发送输入信息
  315. p.StandardInput.WriteLine(str + " &exit");
  316. //%SystemRoot%\system32\
  317. p.StandardInput.AutoFlush = true;
  318. //p.StandardInput.WriteLine("exit");
  319. //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
  320. //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
  321. //获取cmd窗口的输出信息
  322. string output = p.StandardOutput.ReadToEnd();
  323. //StreamReader reader = p.StandardOutput;
  324. //string line=reader.ReadLine();
  325. //while (!reader.EndOfStream)
  326. //{
  327. // str += line + " ";
  328. // line = reader.ReadLine();
  329. //}
  330. p.WaitForExit();//等待程序执行完退出进程
  331. p.Close();
  332. return output;
  333. }
  334. catch (Exception ex){
  335. return "命令执行失败:"+ex.Message;
  336. }
  337. }
  338. }
  339. }