How to compile C# DLL on the fly, Load, and Use

前端 未结 2 806
后悔当初
后悔当初 2020-12-14 13:41

A) compiling C# EXE\'s and DLL\'s on the fly are relatively easy.
B) Executing an EXE means that a new application is run. Loading a DLL means that methods and functions

2条回答
  •  无人及你
    2020-12-14 14:06

    if you have no need to debug, or don't mind to debug the "dynamic" code, with some missing information. you can generate the code in memory.. this will allow you to compile the code several times.. but will not generate a .pdb

    cp.GenerateInMemory = true;
    

    in alternative if you have no need to able to locate the assembly on disk you can ask the compiler to dump all the code in the temp directory and generate a temp name for the dll (wich will always be unique)

    cp.TempFiles = new TempFileCollection(Path.GetTempPath(), false);
    //cp.OutputAssembly = "eventHandler.dll";
    

    in both this cases to access the dll and it's types you can get it from the compiler results

    Assembly assembly = cr.CompiledAssembly; 
    

    not explicitly loading is necessary

    but if non of this situations apply and you must and a physical .dll with a .pdp in a known folder.. the only advice i can give you it to put a version number on the dll.. and in case you don't have a simple way to control the amount of times the dll was compiled you can always resort to a timestamp..

    cp.OutputAssembly = "eventHandler"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".dll";
    

    of course you must realize that every time you compile a new .dll will be loaded into memory and wont be unloaded unless you use separate app domains.. but that goes out of scope for this question..

提交回复
热议问题