[Previous] [Contents] [Next]

Listing an Assembly's Modules

Although most of this tutorial's applications consist of a single module, you can create assemblies that are made up of multiple modules. You can retrieve modules from an Assembly object in two ways. The first is to request an array of all modules. This allows you to iterate through them all and retrieve any needed information. The second is to retrieve a specific module. Let's look at each of these approaches.

To iterate through an assembly's modules, I need to create an assembly with more than one module. I'll do that by moving GetAssemblyName into its own class and putting that class into a file called AssemblyUtils.netmodule, like so: -

using System.Diagnostics;
namespace MyUtilities
{
    public class AssemblyUtils
    {
        public static string GetAssemblyName(string[] args)
        {
            string assemblyName;
            if (0 == args.Length)
            {
                Process p = Process.GetCurrentProcess();
                assemblyName = p.ProcessName + ".exe";
            }
            else
                assemblyName = args[0];
            return assemblyName;
        }
    }
}

The netmodule is then built using the following command: -

csc /target:module AssemblyUtils.cs

The /target:module switch causes the compiler to generate a module for later inclusion in an assembly. The command above will create a file named AssemblyUtils.netmodule. In Chapter 18, I'll cover the different options when creating assemblies and modules in a bit more detail.

At this point, I just want to create a secondary module so that we have something to reflect upon. The application that will use the AssemblyUtils class follows. Note the using statement where the MyUtilities namespace is referenced.

using System;
using System.Reflection;
using MyUtilities;
class GetModulesApp
{
    public static void Main(string[] args)
    {
        string assemblyName = AssemblyUtils.GetAssemblyName(args);
        Console.WriteLine("Loading info for " + assemblyName);
        Assembly a = Assembly.LoadFrom(assemblyName);
        Module[] modules = a.GetModules();
        foreach(Module m in modules)
        {
            Console.WriteLine("Module: " + m.Name);
        }
    }
}

To compile this application and have the AssemblyUtils.netmodule added to its assembly, you'll need to use the following command-line switches: -

csc /addmodule:AssemblyUtils.netmodule GetModules.cs

At this point, you have an assembly with two different modules. To see this, execute the application-the results should be as follows: -

Loading info for GetModulesApp.exe
Module: GetModulesApp.exe
Module: AssemblyUtils.netmodule

As you can see from the code, I simply instantiated an Assembly object and called its GetModules method. From there I iterated through the returned array and printed the name of each one.

[Previous] [Contents] [Next]