1

I have some C# code that accepts a script written in C# itself and executes the script dynamically. I am able to make use of built in libraries by referencing their assemblies as shown below.

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.Data.dll")
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Xml.dll");
cp.ReferencedAssemblies.Add("System.Linq.dll");
cp.ReferencedAssemblies.Add("System.Xml.Linq.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add("System.Net.Http.dll");
...
options.GenerateExecutable = false;
options.GenerateInMemory = true;
CompilerResults results = provider.CompileAssemblyFromSource(options, "<SCRIPT-SOURCE-HERE>");

However, when trying to add an additional library that is not part of the .NET Framework I run into problems. Here I have added the RestSharp library to the project via NuGet and I can confirm that the RestSharp.dll is in the bin directory of the project.

options.ReferencedAssemblies.Add("RestSharp.dll");

I add this to the script I am attempting to compile ...

using RestSharp;

However when trying to compile the script that makes use of the RestSharp library I receive an error ...

Metadata file 'RestSharp.dll' could not be found

What is the best way to refer to the RestSharp assembly?

webworm
  • 10,587
  • 33
  • 120
  • 217
  • Use the full path to the file. – Hans Passant Mar 06 '20 at 18:19
  • @HansPassant how would the path be formatted? Where is the `bin` directory in respect to where the execuation location? `bin/assemblyname.dll`? – webworm Mar 06 '20 at 18:32
  • 1
    I can't guess, you have not said anything about how you are going to deploy your program. If you do it right then it is currently not in bin but in bin\Debug, along with the .exe file. Use Path.GetDirectoryName( Assembly.GetEntryAssembly().Location) to know where it is stored, ought to work on the deployed copy as well. – Hans Passant Mar 06 '20 at 18:45
  • 1
    What ended up working for me was `options.ReferencedAssemblies.Add(typeof(RestSharp.Http).Assembly.Location);`. Now here I did have to specify a class `Http` only because a class name rather than a namespace was expected. I am hoping that by using the `Http` class name that is brings in the assembly path and not just the `Http` class. It compiles though which is good. – webworm Mar 06 '20 at 18:53

0 Answers0