这是不使用 obsoleteAppendPrivatePath
的另一种方法。它捕获一种事件“关联的 dll 未找到”(因此只有在默认目录中找不到 dll 时才会调用它)。
为我工作(.NET 3.5,未测试其他版本)
/// <summary>
/// Here is the list of authorized assemblies (DLL files)
/// You HAVE TO specify each of them and call InitializeAssembly()
/// </summary>
private static string[] LOAD_ASSEMBLIES = { "FooBar.dll", "BarFooFoz.dll" };
/// <summary>
/// Call this method at the beginning of the program
/// </summary>
public static void initializeAssembly()
{
AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs args)
{
string assemblyFile = (args.Name.Contains(','))
? args.Name.Substring(0, args.Name.IndexOf(','))
: args.Name;
assemblyFile += ".dll";
// Forbid non handled dll's
if (!LOAD_ASSEMBLIES.Contains(assemblyFile))
{
return null;
}
string absoluteFolder = new FileInfo((new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).Directory.FullName;
string targetPath = Path.Combine(absoluteFolder, assemblyFile);
try
{
return Assembly.LoadFile(targetPath);
}
catch (Exception)
{
return null;
}
};
}
PS:我没用过AppDomainSetup.PrivateBinPath
,太费劲了。