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
No description
No description
No description
No description
36 Replies
das Vainstaintisch
das VainstaintischOP10mo ago
and i using visual studio(if this information is need)
i like chatgpt
i like chatgpt10mo ago
$code
MODiX
MODiX10mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
das Vainstaintisch
das VainstaintischOP10mo ago
um, here's need to show that this code is wrong and gives an error
leowest
leowest10mo ago
he is asking you to post the images as code so we can better read it and if needed copy paste, modify etc
das Vainstaintisch
das VainstaintischOP10mo ago
uh ok, wait
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 = @"
public class MyScript
{
public void Execute()
{
Console.WriteLine(""Hello, world!"");
}
}
";

// Создание класса
Assembly assembly = Assembly.Load(CompileCode(code));
Type type = assembly.GetType("MyScript");
and..
// Код из переменной
string code = @"
Console.WriteLine(""Hello, world!"");
";

// Создание ScriptEngine
ScriptEngine engine = new ScriptEngine();

// Выполнение кода
engine.Execute(code);
// Код из переменной
string code = @"
Console.WriteLine(""Hello, world!"");
";

// Создание ScriptEngine
ScriptEngine engine = new ScriptEngine();

// Выполнение кода
engine.Execute(code);
leowest
leowest10mo ago
where is ScriptEngine coming from? what library
das Vainstaintisch
das VainstaintischOP10mo ago
because of that it didn't work and Gemini didn't write this library
leowest
leowest10mo ago
I know this one
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();
}
}
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();
}
}
this uses
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
das Vainstaintisch
das VainstaintischOP10mo ago
gives errors
No description
No description
das Vainstaintisch
das VainstaintischOP10mo ago
(translated to english)
No description
leowest
leowest10mo ago
👆 u have to add the nuget
das Vainstaintisch
das VainstaintischOP10mo ago
i've forgotten how i remember i did this few times but.. could you remind how😅
leowest
leowest10mo ago
im not near a pc ... mmm u right click your project then some where there u see nuget or package manager or something
das Vainstaintisch
das VainstaintischOP10mo ago
mhm, found it
das Vainstaintisch
das VainstaintischOP10mo ago
this? right?
No description
das Vainstaintisch
das VainstaintischOP10mo ago
yea, it works so now i need to edit and paste it to my project😅
leowest
leowest10mo ago
no worries glad its working 😉 ScriptEngine was something very old I think I remember seeing it but dont remember where if it works consider $close this thread 🙂
MODiX
MODiX10mo ago
Use the /close command to mark a forum thread as answered
das Vainstaintisch
das VainstaintischOP10mo ago
here's anyways too many code... sorry i've been afk but with ScriptEngine it looks shorter
leowest
leowest10mo ago
I dont know what Script Engine is so I can't help u with that
i like chatgpt
i like chatgpt10mo ago
Internally Script Engine also uses lengthy code. 🙂 https://github.com/suugbut/SuperTrashBin/blob/main/instantiate_from_text_file.cs
das Vainstaintisch
das VainstaintischOP10mo ago
I'll check it later
leowest
leowest10mo ago
if you can link me to what ScriptEngine I might be able to help
das Vainstaintisch
das VainstaintischOP10mo ago
Lengthy.. you mean in string can be longer code?
i like chatgpt
i like chatgpt10mo ago
Script Engine only shortens the boilerplate.
leowest
leowest10mo ago
Ah there is Microsoft.CodeAnalysis.CSharp.Scripting which lets u evaluate code with your code if that is what you're referring to
das Vainstaintisch
das VainstaintischOP10mo ago
I'll try it tomorrow, maybe I just didn't install the right library for this I didn't fully understand you.. sorry...
leowest
leowest10mo ago
give me a second
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();
}
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();
}
u need using Microsoft.CodeAnalysis.CSharp.Scripting;for that, nuget
das Vainstaintisch
das VainstaintischOP10mo ago
Ok, thank you, i'll try it tomorrow If something will go wrong, i'll write
leowest
leowest10mo ago
No description
das Vainstaintisch
das VainstaintischOP10mo ago
i've installed this, but it anyways gives errors ._.
No description
No description
das Vainstaintisch
das VainstaintischOP10mo ago
guuuuuys, heeeeeelp @leowest @always use bool? as primary keys
SinFluxx
SinFluxx10mo ago
What do the errors say?
das Vainstaintisch
das VainstaintischOP10mo ago
wait a sec wait what why it works?? it didn't work just now
das Vainstaintisch
das VainstaintischOP10mo ago
No description
Want results from more Discord servers?
Add your server