-4

I was wondering if anyone knows how I can run if statements from a text file in c#. Thank you.

Extractx
  • 23
  • 3
  • 1
    What do you mean by this? Does the file contain some code? Are you trying to create your own programming language or do you mean something completely different? – Olivier Jacot-Descombes Sep 29 '18 at 17:21
  • The file contains this code: if (oSession.fullUrl=="https://cdn.binw.net/core387.swf") { oSession.fullUrl = "http://bw-####.000webhostapp.com/BW####t2018/core.swf"; } I want to execute that in my c# code – Extractx Sep 29 '18 at 17:24

1 Answers1

1

In C# you can load an assembly at run time programmatically. For this assembly to be usable, it is best to let it implement an interface. It is completely up to you what you put into this interface. E.g.

public interface IMyAddIn
{
    string GetUrl(string parameter);
}

Now, you need at least 3 assemblies, i.e. 3 projects in Visual Studio. One is your executable project (the main project). Another one must be a class library project (DLL) declaring this interface (let's call it the contract). The third one is a class library project (DLL) as well and implements the add-in.

Both, the executable and the add-in projects must reference the contract project.

Now, the executable project can load the add-in like this:

var asm = Assembly.UnsafeLoadFrom(fileName);
string addInInterfaceName = typeof(IMyAddIn).FullName;
foreach (Type type in asm.GetExportedTypes()) {
    Type interfaceType = type.GetInterface(addInInterfaceName);
    if (interfaceType != null &&
        (type.Attributes & TypeAttributes.Abstract) != TypeAttributes.Abstract)
    {
        var addIn = (IMyAddIn)Activator.CreateInstance(type);
        // Let's assume that each add-in has only one class implementing the interface
        return addIn.GetUrl(input);
    }
}

If you don't want to load an assembly but really execute code given as text, see this answer: https://stackoverflow.com/a/29417053/880990

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188