ProcessUtil.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Security.Principal;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace Ips.Library.Basic
  11. {
  12. public class ProcessUtil
  13. {
  14. public static void KillProcessByName(string procName)
  15. {
  16. procName = Path.GetFileNameWithoutExtension(procName);
  17. var procList = Process.GetProcessesByName(procName);
  18. foreach (var proc in procList)
  19. {
  20. proc.Kill();
  21. var success = proc.WaitForExit(3000);
  22. if (!success)
  23. {
  24. throw new Exception($"停止进程失败:{proc.MainModule.FileName}");
  25. }
  26. }
  27. }
  28. /// <summary>
  29. /// 检查当前正在运行的主程序是否是在 Debug 配置下编译生成的。
  30. /// </summary>
  31. public static bool IsDebug
  32. {
  33. get
  34. {
  35. if (_isDebugMode == null)
  36. {
  37. var assembly = Assembly.GetEntryAssembly();
  38. if (assembly == null)
  39. {
  40. // 由于调用 GetFrames 的 StackTrace 实例没有跳过任何帧,所以 GetFrames() 一定不为 null。
  41. assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
  42. }
  43. var debuggableAttribute = assembly.GetCustomAttribute<DebuggableAttribute>();
  44. _isDebugMode = debuggableAttribute.DebuggingFlags
  45. .HasFlag(DebuggableAttribute.DebuggingModes.EnableEditAndContinue);
  46. }
  47. return _isDebugMode.Value;
  48. }
  49. }
  50. private static bool? _isDebugMode;
  51. }
  52. }