从exe目录不同的文件夹中引用.net dll

时间:2014-12-15 11:17:03

标签: c#

我有一个结构: -      \bin\debug\abc.exe和      \Libs\win32\xyz.dll。 现在我需要引用xyz.dll以便运行我的abc.exe。我试过"探测" app.config中的标记,但在这种情况下,只有当我'Libs' ' debug'中的文件夹文件夹,即.exe存在的位置。但我想从.exe中输出2个文件夹,然后进入\Libs\win32以引用.dll。请建议我该怎么做。

2 个答案:

答案 0 :(得分:3)

一个选项是处理AssemblyResolve事件,每次.NET无法在当前路径中找到所需的程序集时,它将触发AssemblyResolve事件:

{
    // Execute in startup
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
}

private Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args)
{
    string RESOURCES = ".resources";
    try
    {
        /* Extract assembly name */
        string[] sections =  args.Name.Split(new char[] { ',' });
        if (sections.Length == 0) return null;

        string assemblyName = sections[0];

        /* If assembly name contains ".resource", you don't need to load it*/
        if (assemblyName.Length >= RESOURCES.Length &&
                assemblyName.LastIndexOf(RESOURCES) == assemblyName.Length - RESOURCES.Length)
        {
            return null;
        }

        /* Load assembly to current domain (also you can use simple way to load) */
        string assemblyFullPath = "..//..//Libs//" + assemblyName;
        FileStream io = new FileStream(assemblyNameWithExtension, FileMode.Open, FileAccess.Read);
        if (io == null) return null;
        BinaryReader binaryReader = new BinaryReader(io);
        Assembly assembly = Assembly.Load(binaryReader.ReadBytes((int)io.Length));

        return assembly;
   }
   catch(Exception ex)
   {}
}

*另一个选项是在项目启动时将所有必需的程序集加载到当前域。

答案 1 :(得分:0)

您在文件路径中使用.. \来上移目录 因此,如果您在 \ bin \ debug \ abc.exe 中,那么您对 \ Libs \ win32 \ xyz.dll 的引用将是

..\..\Libs\win32\xyz.dll

只有在构建项目时才需要这样做,如果您的可执行文件正确引用了dll,它只需要与dll放在同一个文件夹中。

除非您使用dllimport或者您需要在运行时知道dll的确切路径。