c# - 如何从 .NET Core 中的流加载程序集

标签 c# .net .net-core

我正在 .NET Core 控制台应用程序上体验 Roslyn。我试图创建一个程序集并将其编译成内存流。但是加载它似乎缺少一个 API ( that normally works on the regular .NET Framework )

var compilation = CSharpCompilation.Create("MyCompilation",
         syntaxTrees: new[] { pocoTree }, references: new[] { mscorlib, currentAssembly });

var ms = new MemoryStream();
var emitResult = compilation.Emit(ms);

var ourAssembly = Assembly.Load(ms.ToArray()); // Fails to compile here

我收到这个错误:

cannot convert from 'byte[]' to 'System.Reflection.AssemblyName'

.NET Core 中从 Steam 加载的替代方法是什么? (除了物理保存程序集并加载它)

最佳答案

您可以使用 AssemblyLoadContext 从 .NET core 中的流加载程序集:

// requires "System.Runtime.Loader": "4.0.0",
protected virtual Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)
{
    return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(peStream, pdbStream);
}

关于c# - 如何从 .NET Core 中的流加载程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384619/

相关文章:

c# - Blazor.net UI 不渲染任何内容

c# - 从 C# 调用 ARM 模板

c# - 当用户试图关闭使用 Form.ShowDialog() 创建的模态对话框时是否会引发事件?

c# - .NET 中值类型的方法

c# - 在 .net 中添加两个集合的最佳方式

.net - dotnet发布包含额外的文件

c# - LINQ,Left Join,抛出异常...失败,因为物化值为 null

c# - 在 C# .NET 中将字符串列表转换为单引号列表

c# - Silverlight 3 WCF 服务 `CommunicationException` 服务器返回错误 : NotFound

c# - 当目录存在时 ZipFile.ExtractToDirectory 是否抛出异常?