Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Load a text file as a class

Is there any way to load a .txt file as a class, which my main program can then call functions from? I'm basically trying to add mod support to my simple app, where the user can select options from each file. The file follows a similar (but not the same) format, with a bunch of voids (functions) that are called in the main program.

How can I do this? Is that even possible to do (probably not, answering my own question?), considering it wouldn't be compiled along with the rest of the program?

Thanks!

like image 415
Scott Avatar asked Jul 31 '12 23:07

Scott


1 Answers

See me answer to this question: Compile a C# Array at runtime and use it in code?

Essentially, you would want to pull your text file into the CodeDom and compile it. After that, it would likely be helpful to create a few dynamic methods as execution helpers.

  • Receive uploaded file
  • Perform any needed validation on the file
  • Read the file as a string into the CodeDom
  • Deal with any compiler/structure errors
  • Create helper methods using Linq expression trees or dynamic methods so that the linkage between the new class and existing code is bridged with a compiled object (otherwise, all the new methods would need to be invoked using reflection)

var csc = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } } );
var cp = new CompilerParameters() {
    GenerateExecutable = false,
    OutputAssembly = outputAssemblyName,
    GenerateInMemory = true
};

cp.ReferencedAssemblies.Add( "mscorlib.dll" );
cp.ReferencedAssemblies.Add( "System.dll" );

StringBuilder sb = new StringBuilder();

// The string can contain any valid c# code

sb.Append( "namespace Foo{" );
sb.Append( "using System;" );
sb.Append( "public static class MyClass{");
sb.Append( "}}" );

// "results" will usually contain very detailed error messages
var results = csc.CompileAssemblyFromSource( cp, sb.ToString() );

Also, see this topic: Implementing a scripting language in C#. IronPython with the DLR might be suitable for your needs.

like image 184
Tim M. Avatar answered Sep 23 '22 02:09

Tim M.