Search code examples
c#dllassembliescsharpcodeprovider

Possible to set absolute path for references in CSharpCodeProvider?


I'm creating new .cs-files with CodeDom and later want to compile/run them with CSharpCodeProvider but having some problem with references.

The code look like this:

        var provider = new CSharpCodeProvider();
        var compilerparams = new CompilerParameters(
            new[]
            {
                "First.dll",
                "Second.dll"
            })
        {
            GenerateExecutable = false,
            GenerateInMemory = true
        };
        CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, _path);
        if (!results.Errors.HasErrors)
            return results.CompiledAssembly;
        var errors = new StringBuilder("Compiler Errors :\r\n");
        foreach (CompilerError error in results.Errors)
        {
            errors.AppendFormat("Line {0},{1}\t: {2}\n",
                error.Line, error.Column, error.ErrorText);
        }
        throw new Exception(errors.ToString());

"First.dll" and "Second.dll" exists in the same folder as my generated .cs-files and if I run it directly I get error. If I move them to my projects bin directory it work fine, but I would rather just keep them seperated.

Is it possible to set absolute path for "First.dll" and "Second.dll" or a path to a directory that contains all my references instead of moving them to my bin-directory?

I tried to change CompilerParameters to absolute paths but that didn't help.


Solution

  • I found a new solution to fix this problem. Instead of generate in memory I set an output path and return this path. So later when I want to use it I load it with Assembly.LoadFrom() (and it will use all referenced dlls in the same directory).

    Example code,

    How to generate assembly:

        public string CompileCode()
        {
            var provider = new CSharpCodeProvider();
            var outputPath = Path.Combine(Path.GetDirectoryName(_path), "temp.dll");
            var compilerparams = new CompilerParameters(
                new[]
                {
                    @"D:\path\to\referenced\dll",
                    @"D:\path\to\referenced\dll2"
                }, outputPath);
            CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, _path);
            var i = results.PathToAssembly;
            if (!results.Errors.HasErrors)
                return i;
            var errors = new StringBuilder("Compiler Errors :\r\n");
            foreach (CompilerError error in results.Errors)
            {
                errors.AppendFormat("Line {0},{1}\t: {2}\n",
                    error.Line, error.Column, error.ErrorText);
            }
            throw new Exception(errors.ToString());
        }
    

    And to load it:

    Assembly assembly = Assembly.LoadFrom(path);
    //Do stuff with assembly