Is it possible to compile and run C# code at runtime in the new .Net Core (better .Net Standard Platform)? I have seen some examples (.Net Framework), but they used NuGet packages that are not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0)
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Option #1: Use the full C# compiler to compile an assembly, load it and then execute a method from it.
This requires the following packages as dependencies in your project.json:
Then you can use code like this:
Option #2: Use Roslyn Scripting. This will result in much simpler code, but currently requires more setup:
Create NuGet.config to get packages from the Roslyn nightly feed:
Add the following package as a dependency to project.json (notice that this is package from today, you will need different version in the future):
You also need to import
dotnet
(obsolete "Target Framework Moniker", which is nevertheless still used by Roslyn):Now you can finally use Scripting:
Both previous answers didn't work for me in .NET Core 2.2 environment on Windows. More references are needed.
So with the help of https://stackoverflow.com/a/39260735/710069 solution, I have ended up with this code:
Than output library to file:
or to memory stream:
Just adding to @svick option one answer. If you want to keep the assembly in memory (rather than writing to a file) you can use the following method:
This is different that in Net451 where the code is:
My code targets both Net451 and Netstandard so I had to use directives to get around this problem. The full code example is here: