Home >Backend Development >C++ >How Can I Dynamically Execute C# Code from a File in a WPF Application?

How Can I Dynamically Execute C# Code from a File in a WPF Application?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-07 19:37:42557browse

How Can I Dynamically Execute C# Code from a File in a WPF Application?

Dynamic execution of C# code files

Question:

Your WPF C# application comes with a button that needs to execute code stored in a separate text file in the application's runtime directory.

Solution:

To dynamically execute code in a text file, follow these steps:

  1. Compile code: Use a C# compiler (such as CSharpCodeProvider) to compile the code in the text file into an assembly.
  2. Create an instance of a compiled assembly: Use the CreateInstance() method of the System.Reflection.Assembly class to create an instance of a compiled assembly.
  3. Invoking a method: Use the GetMethod() and Invoke() methods of the System.Reflection.Type class to invoke the desired method on the instance.

Here is sample code on how to execute a dynamically compiled class method:

<code class="language-csharp">using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string source =
            @"
namespace Foo
{
    public class Bar
    {
        public void SayHello()
        {
            System.Console.WriteLine(""Hello World"");
        }
    }
}
            ";

            Dictionary<string, string> providerOptions = new Dictionary<string, string>
                {
                    {"CompilerVersion", "v3.5"}
                };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

            CompilerParameters compilerParams = new CompilerParameters
                {GenerateInMemory = true,
                 GenerateExecutable = false};

            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            if (results.Errors.Count != 0)
                throw new Exception("编译失败!");

            object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
            MethodInfo mi = o.GetType().GetMethod("SayHello");
            mi.Invoke(o, null);
        }
    }
}</code>

Following these steps, you can dynamically execute C# code from a code file in a WPF application.

The above is the detailed content of How Can I Dynamically Execute C# Code from a File in a WPF Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn