Program.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace DbMigrate
  9. {
  10. internal static class Program
  11. {
  12. static Program()
  13. {
  14. //设置私有路径
  15. Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  16. AppDomain.CurrentDomain.SetData("PRIVATE_BINPATH", "AddIns;");
  17. var m = typeof(AppDomainSetup).GetMethod("UpdateContextProperty", BindingFlags.NonPublic | BindingFlags.Static);
  18. var funsion = typeof(AppDomain).GetMethod("GetFusionContext", BindingFlags.NonPublic | BindingFlags.Instance);
  19. m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "PRIVATE_BINPATH", "AddIns;" });
  20. //c++dll加入环境变量
  21. if (Directory.Exists("AddIns"))
  22. {
  23. string paths = Environment.GetEnvironmentVariable("PATH");
  24. var dirs = Directory.EnumerateDirectories("AddIns", "*", SearchOption.AllDirectories);
  25. List<string> list = new List<string>
  26. {
  27. Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIns")
  28. };
  29. foreach (var item in dirs)
  30. {
  31. list.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, item));
  32. }
  33. Environment.SetEnvironmentVariable("PATH", $"{paths};{string.Join(";", list)}");
  34. }
  35. AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
  36. {
  37. var ex = e.ExceptionObject as Exception;
  38. while (ex.InnerException != null)
  39. ex = ex.InnerException;
  40. MessageBox.Show("出现未处理的异常,程序即将退出!");
  41. };
  42. Application.ThreadException += (sender, e) =>
  43. {
  44. var ex = e.Exception;
  45. while (ex.InnerException != null)
  46. ex = ex.InnerException;
  47. MessageBox.Show($"出现未处理的线程异常!{e.Exception.Message}");
  48. };
  49. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  50. }
  51. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  52. {
  53. var name = args.Name.Split(',')[0];
  54. var dll1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIns", $"{name}.dll");
  55. if (File.Exists(dll1))
  56. return Assembly.Load(dll1);
  57. var dll2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll");
  58. if (File.Exists(dll2))
  59. return Assembly.Load(dll2);
  60. return null;
  61. }
  62. /// <summary>
  63. /// 应用程序的主入口点。
  64. /// </summary>
  65. [STAThread]
  66. static void Main()
  67. {
  68. Application.EnableVisualStyles();
  69. Application.SetCompatibleTextRenderingDefault(false);
  70. Application.Run(new Form1());
  71. }
  72. }
  73. }