🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / C# RMOS / c# kodunu dynamic olarak çalıştırmak CompileAndRunCode CSharpCodeProvider

1-) C# RMOS - c# kodunu dynamic olarak çalıştırmak CompileAndRunCode CSharpCodeProvider

 

 

 

using System;

using System.Windows.Forms;

using Microsoft.CSharp;

using System.CodeDom.Compiler;

namespace Deneme2

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            try

            {

                string csharpCode = @"

            using System;

            public class DynamicClass

            {

                public void Run()

                {

                    Console.WriteLine(""Merhaba, dünya!"");

                }

            }

        ";

                CompileAndRunCode(csharpCode);

            }

            catch (Exception ex)

            {

                MessageBox.Show("Hata Oluştu: " + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        static void CompileAndRunCode(string code)

        {

            CSharpCodeProvider provider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateInMemory = true;

            parameters.GenerateExecutable = false;

            CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);

            if (results.Errors.Count == 0)

            {

                Type dynamicType = results.CompiledAssembly.GetType("DynamicClass");

                dynamic instance = Activator.CreateInstance(dynamicType);

                // Çalıştırılacak metodu burada çağırabilirsiniz

                instance.Run();

            }

            else

            {

                Console.WriteLine("Hata oluştu:");

                foreach (CompilerError error in results.Errors)

                {

                    Console.WriteLine(error.ErrorText);

                }

            }

        }

 

    }

}

 

 

 2024 Ocak 06 Cumartesi
 238