Tools.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using IWshRuntimeLibrary;
  2. using SWRIS.Core;
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. namespace SWRIS.Extensions
  11. {
  12. public static class Tools
  13. {
  14. #region 获取 本周、本月、本季度、本年 的开始时间或结束时间
  15. /// <summary>
  16. /// 获取结束时间
  17. /// </summary>
  18. /// <param name="timeType">Week、Month、Season、Year</param>
  19. /// <param name="time"></param>
  20. /// <returns></returns>
  21. public static DateTime GetTimeStartByType(string timeType, DateTime time)
  22. {
  23. switch (timeType)
  24. {
  25. case "Day":
  26. return time.Date;
  27. case "Week":
  28. DayOfWeek firstDay = DayOfWeek.Monday; // 周一为第一天
  29. return time.AddDays(-((7 + (time.DayOfWeek - firstDay)) % 7));
  30. case "Month":
  31. return time.AddDays(-time.Day + 1);
  32. case "Season":
  33. var time1 = time.AddMonths(0 - ((time.Month - 1) % 3));
  34. return time1.AddDays(-time1.Day + 1);
  35. case "Year":
  36. return time.AddDays(-time.DayOfYear + 1);
  37. default:
  38. return time;
  39. }
  40. }
  41. /// <summary>
  42. /// 获取结束时间
  43. /// </summary>
  44. /// <param name="timeType">Week、Month、Season、Year</param>
  45. /// <param name="time"></param>
  46. /// <returns></returns>
  47. public static DateTime GetTimeEndByType(string timeType, DateTime time)
  48. {
  49. switch (timeType)
  50. {
  51. case "Day":
  52. return time.Date.AddDays(1).AddSeconds(-1);
  53. case "Week":
  54. DayOfWeek firstDay = DayOfWeek.Monday; // 周一为第一天
  55. return time.AddDays(-((7 + (time.DayOfWeek - firstDay)) % 7) + 7).AddSeconds(-1);
  56. case "Month":
  57. return time.AddMonths(1).AddDays(-time.AddMonths(1).Day + 1).AddSeconds(-1);
  58. case "Season":
  59. var time1 = time.AddMonths((3 - ((time.Month - 1) % 3) - 1));
  60. return time1.AddMonths(1).AddDays(-time1.AddMonths(1).Day + 1).AddSeconds(-1);
  61. case "Year":
  62. var time2 = time.AddYears(1);
  63. return time2.AddDays(-time2.DayOfYear).AddSeconds(-1);
  64. default:
  65. return time;
  66. }
  67. }
  68. #endregion
  69. public static string GetWeek(int week)
  70. {
  71. switch (week)
  72. {
  73. case 1:
  74. return "星期一";
  75. case 2:
  76. return "星期二";
  77. case 3:
  78. return "星期三";
  79. case 4:
  80. return "星期四";
  81. case 5:
  82. return "星期五";
  83. case 6:
  84. return "星期六";
  85. case 7:
  86. return "星期日";
  87. default:
  88. return "星期日";
  89. }
  90. }
  91. public static string GetIpAddress()
  92. {
  93. string ip = string.Empty;
  94. foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
  95. {
  96. if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
  97. {
  98. if ("127.0.0.1" == _IPAddress.ToString())
  99. {
  100. continue;
  101. }
  102. else
  103. {
  104. ip = _IPAddress.ToString();
  105. break;
  106. }
  107. }
  108. }
  109. return ip;
  110. }
  111. /// <summary>
  112. /// 检查指定的IP地址是否存在于本机的网络接口中
  113. /// </summary>
  114. /// <param name="targetIp"></param>
  115. /// <returns></returns>
  116. public static bool CheckIpAddressExists(string targetIp)
  117. {
  118. // 获取所有网络接口
  119. NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
  120. foreach (NetworkInterface ni in interfaces)
  121. {
  122. // 只获取运行中的接口
  123. if (ni.OperationalStatus == OperationalStatus.Up)
  124. {
  125. IPInterfaceProperties ipProperties = ni.GetIPProperties();
  126. // 获取该接口的所有IP地址
  127. foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
  128. {
  129. if (ip.Address.ToString() == targetIp)
  130. {
  131. return true;
  132. }
  133. }
  134. }
  135. }
  136. return false;
  137. }
  138. /// <summary>
  139. /// 检查指定端口是否被占用
  140. /// </summary>
  141. /// <param name="port"></param>
  142. /// <returns></returns>
  143. public static bool CheckPortInUse(int port)
  144. {
  145. int currentProcessId = Process.GetCurrentProcess().Id;
  146. var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
  147. var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();
  148. foreach (var ep in tcpListeners)
  149. {
  150. if (ep.Port == port)
  151. {
  152. // 用命令行查询占用端口的进程
  153. var processId = GetProcessIdByPort(port);
  154. if (processId.HasValue && processId.Value != currentProcessId)
  155. {
  156. return true; // 被其他进程占用
  157. }
  158. return false; // 被自己占用或未占用
  159. }
  160. }
  161. return false;
  162. }
  163. /// <summary>
  164. /// 使用netstat获取端口对应的进程ID
  165. /// </summary>
  166. /// <param name="port"></param>
  167. /// <returns></returns>
  168. private static int? GetProcessIdByPort(int port)
  169. {
  170. try
  171. {
  172. var startInfo = new ProcessStartInfo
  173. {
  174. FileName = "netstat",
  175. Arguments = "-ano",
  176. UseShellExecute = false,
  177. RedirectStandardOutput = true,
  178. RedirectStandardError = true,
  179. CreateNoWindow = true
  180. };
  181. using (Process process = Process.Start(startInfo))
  182. {
  183. string output = process.StandardOutput.ReadToEnd();
  184. foreach (string line in output.Split('\n'))
  185. {
  186. if (line.Contains("TCP") && line.Contains($":{port}") && line.Contains("LISTENING"))
  187. {
  188. var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  189. if (parts.Length >= 5 && int.TryParse(parts[4], out int pid))
  190. {
  191. return pid;
  192. }
  193. }
  194. }
  195. }
  196. }
  197. catch { }
  198. return null;
  199. }
  200. public static byte[] GetMD5Bytes(string input)
  201. {
  202. using (MD5 md5 = MD5.Create())
  203. {
  204. byte[] inputBytes = Encoding.UTF8.GetBytes(input);
  205. byte[] hashBytes = md5.ComputeHash(inputBytes);
  206. return hashBytes;
  207. }
  208. }
  209. /// <summary>
  210. /// DateTime 转换为时间戳
  211. /// </summary>
  212. public static int DateTimeToTimestamp(this DateTime time)
  213. {
  214. DateTimeOffset dto = new DateTimeOffset(time);
  215. return (int)(dto.ToUnixTimeSeconds());
  216. }
  217. /// <summary>
  218. /// 时间戳转换为DateTime
  219. /// </summary>
  220. public static DateTime TimestampToDateTime(this int timestamp)
  221. {
  222. DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(timestamp);
  223. return dto.LocalDateTime;
  224. }
  225. /// <summary>
  226. /// 创建桌面会计快捷方式,要求管理员权限运行
  227. /// </summary>
  228. /// <param name="applicationPath"></param>
  229. /// <param name="shortcutName"></param>
  230. /// <returns></returns>
  231. public static bool CreateShortcut(string applicationPath, string shortcutName)
  232. {
  233. string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  234. string shortcutPath = Path.Combine(desktopPath, shortcutName + ".lnk");
  235. // 检查快捷方式是否已存在
  236. if (System.IO.File.Exists(shortcutPath))
  237. {
  238. return false; // 已存在,不创建
  239. }
  240. try
  241. {
  242. WshShell shell = new WshShell();
  243. IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
  244. shortcut.TargetPath = applicationPath;
  245. shortcut.WorkingDirectory = Path.GetDirectoryName(applicationPath);
  246. shortcut.Description = "需要管理员权限运行";
  247. shortcut.IconLocation = applicationPath + ",0";
  248. // 保存快捷方式
  249. shortcut.Save();
  250. // 修改快捷方式以要求管理员权限
  251. using (var fs = new FileStream(shortcutPath, FileMode.Open, FileAccess.ReadWrite))
  252. {
  253. fs.Seek(21, SeekOrigin.Begin);
  254. fs.WriteByte(0x22); // 设置标志位以管理员身份运行
  255. }
  256. return true; // 创建成功
  257. }
  258. catch
  259. {
  260. // 如果创建过程中出错,尝试删除可能已部分创建的快捷方式
  261. if (System.IO.File.Exists(shortcutPath))
  262. {
  263. try { System.IO.File.Delete(shortcutPath); } catch { }
  264. }
  265. throw;
  266. }
  267. }
  268. public static void OpenUrl(string url)
  269. {
  270. try
  271. {
  272. Process.Start(new ProcessStartInfo
  273. {
  274. FileName = url,
  275. UseShellExecute = true // 使用系统默认浏览器
  276. });
  277. }
  278. catch (Exception ex)
  279. {
  280. LogHelper.Error($"打开网页失败:{ex.Message}", ex);
  281. }
  282. }
  283. }
  284. }