9

I am compiling classes at run-time using the CodeDomProvider class. This works fine for classes only using the System namespace:

using System;

public class Test
{
    public String HelloWorld()
    {
        return "Hello World!";
    }
}

If I try to compile a class using System.Web.UI.WebControls though, I get this error:

{error CS0006: Metadata file 'System.Web.UI.WebControls' could not be found} System.CodeDom.Compiler.CompilerError

Here's a snippet of my code:

var cp = new CompilerParameters();

cp.ReferencedAssemblies.Add("System.Web.UI.WebControls");

How do I reference the System.Web.UI.WebControls namespace?

starblue
  • 55,348
  • 14
  • 97
  • 151
cllpse
  • 21,396
  • 37
  • 131
  • 170

3 Answers3

44

You can loop through all the currently loaded assemblies:

var assemblies = AppDomain.CurrentDomain
                            .GetAssemblies()
                            .Where(a => !a.IsDynamic)
                            .Select(a => a.Location);   

cp.ReferencedAssemblies.AddRange(assemblies.ToArray());
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Dan Nuffer
  • 665
  • 1
  • 6
  • 11
16

You reference assemblies, not namespaces. You should use MSDN to look up the name of the assembly that contains the classes you need to use: in this case it's going to be:

var cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.Web.dll");
Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • Doesn't work for me. Do you think I should supply the full path to the assembly? If yes; how might I do that dynamically? – cllpse Apr 27 '09 at 14:07
  • 3
    Ah, System.Web.UI.WebControls.dll doesn't exist -- the classes in that namespace live in System.Web.dll instead. – Tim Robinson Apr 27 '09 at 14:17
6

This proved to be a little less brute force in my case. I was building an addin and there were 730 assemblies loaded in the current domain so there was major lag involved.

var assemblies = someType.Assembly.GetReferencedAssemblies().ToList();
   var assemblyLocations =  
assemblies.Select(a => 
     Assembly.ReflectionOnlyLoad(a.FullName).Location).ToList();

assemblyLocations.Add(someType.Assembly.Location);

cp.ReferencedAssemblies.AddRange(assemblyLocations.ToArray());
jwize
  • 4,230
  • 1
  • 33
  • 51
  • 1
    +1. I used your proposal and worked great. Just you need to edit the last line and write `cp.ReferencedAssemblies.AddRange(assemblyLocations.ToArray());` instead. – Luis Quijada Sep 05 '12 at 17:31