首页 > 解决方案 > 如何在c#中加载或添加引用并在其他应用程序域中使用它

问题描述

当我将我的 dll 加载到我的其他应用程序域时,它已正确加载,但是当我执行 dll 所需的 exe 时,它​​会抛出异常

此代码来自 StackOverFlow 上的另一个问题

我的代码:

  static void Main(string[] args)
    {

        AppDomain app = AppDomain.CreateDomain("seco");



        //my dll that i want to add to my app domain
        string path = @"D:\vs projects\ConsoleApplication17\ConsoleApplication17\bin\Debug\lom.dll";

        Type type = typeof(Proxy);
        var asmLoaderProxy = (Proxy)app.CreateInstanceAndUnwrap(

            type.Assembly.FullName, 

            type.FullName);


        asmLoaderProxy.GetAssembly(path); //load succed here 


        // the exe that needs to the dll 
        app.ExecuteAssembly("op.exe"); // -> throw exception FileNotFoundException here

        AppDomain.Unload(app);



        Console.WriteLine("finished");
        Console.ReadKey();
    }

    [Serializable]
    public class Proxy 
    {
        public Assembly GetAssembly(string assemblyPath)
        {
            try
            {
                return Assembly.LoadFrom(assemblyPath);
            }
            catch (Exception)
            {
                return null;
                // throw new InvalidOperationException(ex);
            }
        }
    }

}

我的错误是什么?注意-> dll 有一个类,该类有一个打印“在 dll 中打印你好”的方法

并且exe从类中获取实例并调用该方法

谢谢 :)

标签: c#visual-studioappdomain

解决方案


根据你的描述,我做一个测试。

但是,我发现我可以成功运行代码,没有任何异常。

这里我要提一下,我们需要使用绝对路径"op.exe"

喜欢:@"D:\sample\TestDll\ConsoleApp1\bin\Debug\op.exe"

希望这可以帮到你。


推荐阅读