- Regresar »
- Assembly , Reflection »
- How to get assembly version without loading it
Publicado por: Carlos
miércoles, marzo 21, 2012
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.Copy failes 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.GetAssemblyName won't load the assembly, so we can change the file afterwards.
Fuente
