views:

1408

answers:

2

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?

+4  A: 

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
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?
roosteronacid
Ah, System.Web.UI.WebControls.dll doesn't exist -- the classes in that namespace live in System.Web.dll instead.
Tim Robinson
+5  A: 

You can loop through all the currently loaded assemblies:

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
    try
    {
        string location = assembly.Location;
        if (!String.IsNullOrEmpty(location))
        {
            cp.ReferencedAssemblies.Add(location);
        }
    }
    catch (NotSupportedException)
    {
        // this happens for dynamic assemblies, so just ignore it.
    }
}
Dan Nuffer