Dynamically Loading .NET Assembly (32-bit or 64-bit)

Found a nice technique for dynamically loading a native .NET assembly and automatically choosing the appropriate one to match the loading process’s address space (32-bit or 64-bit). The source is located here: http://www.chilkatforum.com/questions/2966/why-separate-32-and-64-bit-chilkat-libraries-for-net and reproduced here:

I prefer another solution to this problem. It allows you to have a mix of 32 and 64 bit apps in the same directory.

I install both 32 and 64 bit assemblies into the same directory by renaming them.


In the project references you just refer to the one you want for that particular project.

Then I get them to load using the AssemblyResolve event which fires when a dll can’t be found.

In Program.Main() add this

	AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

Then add this code somewhere

	private const string ChilkatRootFileName = "ChilkatDotNet4";

	static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
		if (args.Name.StartsWith(ChilkatRootFileName, StringComparison.InvariantCultureIgnoreCase))
			string path = string.Empty;
			string current_folder = string.Empty;
				current_folder = Path.GetDirectoryName(new Uri(
				path = Path.Combine(current_folder, ChilkatRootFileName + 
					string.Format("-{0}.dll", IntPtr.Size == 4 ? "32" : "64"));
				Assembly assembly = Assembly.LoadFrom(path);
				return assembly;
			catch (Exception ex)
		return null;