3

我发现以下代码从自定义位置动态加载 dll:

private void Form1_Load(object sender, EventArgs e)
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
}

private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
    string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string assemblyPath = Path.Combine(folderPath, "libs", new AssemblyName(args.Name).Name + ".dll");
    if (File.Exists(assemblyPath) == false) return null;
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    return assembly;
}

private void button1_Click(object sender, EventArgs e)
{
    var zip = ZipFile.Read("test.zip");

    foreach (ZipEntry file in zip)
    {
        file.Extract(".", ExtractExistingFileAction.OverwriteSilently);
    }
}

在某些情况下,此解决方案有效,但使用 ZipDotNet dll 我得到:

InnerException  {"File or assembly name \"Ionic.Zip, Version=1.9.1.8, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c\" or one of its dependencies, was not found. Operation is not supported. (Exception from HRESULT: 0x80131515)":"Ionic.Zip, Version=1.9.1.8, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c"}   System.Exception {System.IO.FileLoadException}


自从它通过以来,if (File.Exists(assemblyPath) == false) return null;我猜它是加载 Ionic.Zip.dll 的依赖项的问题?我也将如何解决它们?

4

1 回答 1

4

在这里查看Iconic.Zip.dll 的源代码,我看到项目中唯一的引用是 System、System.Data、System.Security 和 System.Xml,所以我怀疑原因是您无法加载它的任何引用。

我认为您的程序集解析方法有点太简单了。假设程序集名称与文件名相同,但情况并非总是如此。因此,您可以做的是获取AssemblyName目标文件夹中的每个 dll 并存储名称到文件的映射。然后,当解析器请求一个名称时,您在已知名称中查找它并加载程序集文件。这是该想法的快速实现。

private Dictionary<string, string> assemblyNameToFileMapping = new Dictionary<string, string>();

private void Form1_Load(object sender, EventArgs e)
{
    GetAssemblyNames();
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
}

private void GetAssemblyNames()
{
  string folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "libs");
  foreach(string file in Directory.EnumerateFiles(folderPath, "*.dll"))
  {
     try
     {
         AssemblyName name = AssemblyName.GetAssemblyName(file);
         assemblyNameToFileMapping.Add(name.FullName, file);
     }
     catch { } // Just move on if we can't get the name.
  }
}

private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
    string file;
    if (assemblyNameToFileMapping.TryGetValue(args.Name, out file))
    {
       return Assembly.LoadFrom(file);
    }
    return null;
}
于 2013-03-19T08:46:32.380 回答