Specify where to look for referenced Assemblies in C# Application

When you design an application it always a good idea to split your code into different modules. Clubbing all the methods, objects which are related to each other together. Inadvertently you may have to define different classes to meet this objective. More often than not you would have separate assemblies or DLL’s which contain this class and have it referenced in your application.

When you run the application which has reference different assemblies, the CLR will look for those assemblies in some predefined locations. By default the CLR would look for the referenced DLL’s in the following locations

  • Check if application configuration file is specified. If yes check if the <codebase>/<probing> node for the assembly is specified. 
  • If the application configuration file is not specified, the machine configuration file is used, which uses the following strategy
    • The same folder as the referencing/calling assembly
    • Folder with the name of the assembly

E.g.

  • Create an application MyApp.exe which references an assembly MyAssembly.dll. S
  • ave the application to the C:\Application folder.
  • Execute the  MyApp.exe

When you execute the application, the CLR will try to load the  MyAssembly.dll when a reference is made to it, from the following locations (since the application configuration file is not specified, the default machine configuration file will be used)

  • C:\Application\MyAssembly.dll
  • C:\Application\MyAssembly\MyAssembly.dll
  • C:\Application\MyAssembly.exe
  • C:\Application\MyAssembly\MyAssembly.exe

If you wish to control the location where the CLR needs to search for assemblies, you need to create a Application Configuration file for the MyApp.exe. The application configuration file should be named as MyApp.exe.config. In the config file either specify the CodeBase node or Probing node. Using the probing node is much simpler, since it does not need the assembly to be strongly named to be referenced, which is a required for using CodeBase node.

E.g. of using Probing node in the configuration file

<configuration>
   <runtime>
      <assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
         <probing privatePath=”bin;PlugIns;Images\Icons;”/>
      </assemblyBinding>
   </runtime>
</configuration>

The privatePath attribute of the probing element indicates where to search for referenced assemblies, in this case it will search in “bin”, “PlugIns”, “Images\Icons”

Using this technique you can group your assemblies in self describing folders. This is a very powerful technique to organize your application.

References:

.NET Configuration Files

How the Runtime Locates Assemblies

Specifying an Assembly’s Location

Machine Configuration Files

Application Configuration Files

Locating the Assembly through Codebases or Probing