views:

147

answers:

3

This might be a strange question.

I need to late bind an uncompiled c# class (.cs). Not even sure if this is possible. The class won't be part of the project or referenced. The only thing I'll know about it is its file location.

The file wont be compiled at execution time as it will be part of a website app_code. Simply just trying to create an instance of it and then call a function on it.

Is this even possible?

Thanks in advance

+1  A: 

It sounds like you want to compile and reference your class at runtime. This is definitely possible.

This article should point you in the right direction... http://support.microsoft.com/kb/304655

Keep in mind that once you load an assembly into memory, you cannot unload it unless you unload the entire App Domain. So if you need to be able to unload your code, you will have to load it into a new AppDomain.

willem
+1  A: 

You didn't ask about compiling, so I assume you just want to instantiate the class and use it.

You should make the class implement an interface covering the functionality you need, and then you can instantiate it using the Activator class:

ObjectHandle fooHandle = Activator.CreateInstanceFrom(
   @"C:\somePath\FooAssembly.dll", "FooNamespace.Foo");
IFoo foo = (IFoo)fooHandle.Unwrap();

The class should have a default constructor. When loading assemblies by name as above, consider security implications.

dbkk
A: 

You can use the CodeProvider classes

CodeDomProvider cdp = Microsoft.CSharp.CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults cr = cdp.CompileAssemblyFromFile(<CompilerParameters>,<string [] of files to compiler>);

just replace with the correct object for you needs and with the string array of the actual file names.

you can also load the code into a string and compile straight from there

The resulting assembly can then be found in

cr.CompiledAssembly
monkey_p