Tools.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 | findstr :{port}",
  176. UseShellExecute = false,
  177. RedirectStandardOutput = true,
  178. CreateNoWindow = true
  179. };
  180. using (Process process = Process.Start(startInfo))
  181. {
  182. string output = process.StandardOutput.ReadToEnd();
  183. foreach (string line in output.Split('\n'))
  184. {
  185. if (line.Contains($"TCP") && line.Contains($":{port}") && line.Contains("LISTENING"))
  186. {
  187. var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  188. if (parts.Length >= 5 && int.TryParse(parts[4], out int pid))
  189. {
  190. return pid;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. catch { }
  197. return null;
  198. }
  199. public static byte[] GetMD5Bytes(string input)
  200. {
  201. using (MD5 md5 = MD5.Create())
  202. {
  203. byte[] inputBytes = Encoding.UTF8.GetBytes(input);
  204. byte[] hashBytes = md5.ComputeHash(inputBytes);
  205. return hashBytes;
  206. }
  207. }
  208. /// <summary>
  209. /// DateTime 转换为时间戳
  210. /// </summary>
  211. public static int DateTimeToTimestamp(this DateTime time)
  212. {
  213. DateTimeOffset dto = new DateTimeOffset(time);
  214. return (int)(dto.ToUnixTimeSeconds());
  215. }
  216. /// <summary>
  217. /// 时间戳转换为DateTime
  218. /// </summary>
  219. public static DateTime TimestampToDateTime(this int timestamp)
  220. {
  221. DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(timestamp);
  222. return dto.LocalDateTime;
  223. }
  224. /// <summary>
  225. /// 创建桌面会计快捷方式,要求管理员权限运行
  226. /// </summary>
  227. /// <param name="applicationPath"></param>
  228. /// <param name="shortcutName"></param>
  229. /// <returns></returns>
  230. public static bool CreateShortcut(string applicationPath, string shortcutName)
  231. {
  232. string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  233. string shortcutPath = Path.Combine(desktopPath, shortcutName + ".lnk");
  234. // 检查快捷方式是否已存在
  235. if (System.IO.File.Exists(shortcutPath))
  236. {
  237. return false; // 已存在,不创建
  238. }
  239. try
  240. {
  241. WshShell shell = new WshShell();
  242. IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
  243. shortcut.TargetPath = applicationPath;
  244. shortcut.WorkingDirectory = Path.GetDirectoryName(applicationPath);
  245. shortcut.Description = "需要管理员权限运行";
  246. shortcut.IconLocation = applicationPath + ",0";
  247. // 保存快捷方式
  248. shortcut.Save();
  249. // 修改快捷方式以要求管理员权限
  250. using (var fs = new FileStream(shortcutPath, FileMode.Open, FileAccess.ReadWrite))
  251. {
  252. fs.Seek(21, SeekOrigin.Begin);
  253. fs.WriteByte(0x22); // 设置标志位以管理员身份运行
  254. }
  255. return true; // 创建成功
  256. }
  257. catch
  258. {
  259. // 如果创建过程中出错,尝试删除可能已部分创建的快捷方式
  260. if (System.IO.File.Exists(shortcutPath))
  261. {
  262. try { System.IO.File.Delete(shortcutPath); } catch { }
  263. }
  264. throw;
  265. }
  266. }
  267. public static void OpenUrl(string url)
  268. {
  269. try
  270. {
  271. Process.Start(new ProcessStartInfo
  272. {
  273. FileName = url,
  274. UseShellExecute = true // 使用系统默认浏览器
  275. });
  276. }
  277. catch (Exception ex)
  278. {
  279. LogHelper.Error($"打开网页失败:{ex.Message}", ex);
  280. }
  281. }
  282. }
  283. }