using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace LicenseExamination
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += LoadDirDll.AssemblyResolve;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
}
/// <summary> 已加载DLL
/// </summary>
private static Dictionary<string, Assembly> LoadedDlls = new Dictionary<string, Assembly>();
/// </summary>
/// <summary> 在对程序集解释失败时触发
/// </summary>
/// <param name="sender">AppDomain</param>
/// <param name="args">事件参数</param>
public static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
var assName = new AssemblyName(args.Name).FullName;
try
{
//判断是否已经加载
if (LoadedDlls.ContainsKey(assName))
{
return LoadedDlls[assName];
}
string file = Application.StartupPath + "\\libs\\" + assName.Split(',')[0] + ".dll";
byte[] buff = System.IO.File.ReadAllBytes(file);
var da = Assembly.Load(buff);
return da;
}
catch (Exception ex)
{
throw new DllNotFoundException(assName);//否则抛出加载失败的异常
}
}
}
}
main函数前面增加解析事件注册
AppDomain.CurrentDomain.AssemblyResolve += LoadDirDll.AssemblyResolve;
string file = Application.StartupPath + "\\libs\\"
可修改为任意目录
根据区域语言加载dll
using System.Reflection;
using System.IO;
using System.Globalization;
public class Program
{
/// <summary>
/// 使用静态构造函数来绑定解析程序集失败事件
/// </summary>
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
}
[STAThreadAttribute]
public static void Main()
{
App.Main(); //启动WPF项目
}
//解析程序集失败,会加载对应的程序集
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
var path = assemblyName.Name + ".dll";
//判断程序集的区域性
if (!assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture))
{
path = string.Format(@"{0}\{1}", assemblyName.CultureInfo, path);
}
using (Stream stream = executingAssembly.GetManifestResourceStream(path))
{
if (stream == null) return null;
var assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
}