How can i compile code, that is located in variable string?
How can i compile code, that is located in variable string? i asked this question to chat gpt and google geminш, but they gave me only only these options that didn't work



$codegif in chat



using Microsoft.CodeAnalysis.CSharp.Scripting;for that, nugetusing Microsoft.CodeAnalysis.CSharp.Scripting;string code = @"
public class MyScript
{
public void Execute()
{
Console.WriteLine(""Hello, world!"");
}
}
";
// Создание класса
Assembly assembly = Assembly.Load(CompileCode(code));
Type type = assembly.GetType("MyScript");// Код из переменной
string code = @"
Console.WriteLine(""Hello, world!"");
";
// Создание ScriptEngine
ScriptEngine engine = new ScriptEngine();
// Выполнение кода
engine.Execute(code);internal class Program
{
static void Main(string[] args)
{
string code = @"
using System;
class HelloWorld
{
static void Main()
{
System.Console.WriteLine(""Hello, World!"");
}
}
";
string trustedAssemblies = (AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string)!;
string[] trustedList = trustedAssemblies.Split(';');
var required = new List<string>()
{
"mscorlib.dll",
"System.Private.CoreLib.dll",
"System.Runtime.dll",
"System.Console.dll",
};
var path = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
var filteredPathList = trustedList.Where(p => required.Any(r => p.Contains(r))).Select(x => Path.Combine(path, x)).ToList();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
var outputFilePath = "HelloWorld.exe";
var compilation = CSharpCompilation.Create("DynamicCode")
.WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
.AddReferences(filteredPathList.Select(assembly => MetadataReference.CreateFromFile(assembly)).ToList())
.AddSyntaxTrees(syntaxTree);
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (result.Success)
{
File.WriteAllBytes(outputFilePath, ms.ToArray());
Console.WriteLine("Compilation successful. Output file: " + outputFilePath);
}
else
{
Console.WriteLine("Compilation failed. Errors:");
foreach (var diagnostic in result.Diagnostics)
{
Console.WriteLine(diagnostic.ToString());
}
}
Console.ReadKey();
}
}using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;static async Task Main(string[] args)
{
var codeToCompile = @"Console.WriteLine(""Hello, world!"");";
var options = ScriptOptions.Default;
options = options.WithImports("System", "System.Console");
Script compiledScript = CSharpScript.Create(codeToCompile, options);
Console.WriteLine("Executing code...");
var result = await compiledScript.RunAsync();
Console.WriteLine(result.ReturnValue);
Console.WriteLine("Code executed...");
Console.ReadKey();
}