Retired Microsoft Blog disclaimer

This directory is a mirror of retired "Decrypt My World" MSDN blog and is provided as is. All posting authorship and copyrights belong to respective authors.
Original URL: https://blogs.msdn.microsoft.com/alejacma/2008/09/05/how-to-get-assembly-version-without-loading-it/
Post name: How to get assembly version without loading it
Original author: Alejandro Campos Magencio
Posting date: 2008-09-05T09:00:00+00:00


Hi all,


The other day I was trying to add a simple autoupdate functionality to a little tool I developed, and I needed to check the version of current assembly against the udpated one. If current assembly was older than the updated one, I needed to substitute the older one with the newer. Plain and simple.


This was my first attempt to achieve this (code has been simplified):

using System.Reflection;
using System.IO;

...

// Get current and updated assemblies
Assembly currentAssembly = Assembly.LoadFile(currentAssemblyPath);
Assembly updatedAssembly = Assembly.LoadFile(updatedAssemblyPath);

AssemblyName currentAssemblyName = currentAssembly.GetName();
AssemblyName updatedAssemblyName = updatedAssembly.GetName();

// Compare both versions
if (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0)
{
// There's nothing to update
return;
}

// Update older version
File.Copy(updatedAssemblyPath, currentAssemblyPath, true);


But File.Copyfailes because current assembly is in use. Why? Because of Assembly.LoadFile. When we load an assembly no other process (including ours) can change or delete the file because we are using it. The issue is that we can't unload an assembly that we loaded in an AppDomain unless the AppDomain itself gets unloaded. Here I'm using the default AppDomain which will only get unloaded when the application exits. So then I tried creating a new AppDomain, load the assemblies in there and unload the AppDomain afterwards before changing the file. It didn't help either. So...


How can we get the assembly version without loading the assembly? The solution is easy:

using System.Reflection;
using System.IO;

...

// Get current and updated assemblies
AssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyPath);
AssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName(updatedAssemblyPath);

// Compare both versions
if (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0)
{
// There's nothing to update
return;
}

// Update older version
File.Copy(updatedAssemblyPath, currentAssemblyPath, true);


AssemblyName.GetAssemblyNamewon't load the assembly, so we can change the file afterwards.


I hope this helps.


Kind regards,



Alex (Alejandro Campos Magencio)



PS: In case you are interested, I will post my simple autoupdate code one of these days, once I have time to change a couple of things on it.


Share this article:

Comments:

Comments are closed.