How to detect .NET Framework version of an Assembly

  • Thread starter Thread starter Hayato Iriumi
  • Start date Start date
H

Hayato Iriumi

Hello,
I have a need to know which version of the .NET Framework an assembly
was compiled against. Well, I found a way to do it by detecting
Assembly.ImageRuntimeVersion, but once I load the assembly, I cannot
delete the file because the file is held by the upgrade application
after I load the assembly. The reason I want to be able to delete is
that I'm writing an application to upgrade a Windows Service written
in .NET. By using System.Reflection.Assembly.Load(), there isn't a way
to unload the assembly.

So let's say I have a Windows Service executable written against .NET
Framework 1.1 and I need to upgrade it to the Windows Service written
against .NET Framework 2.0. If I already know that the executable was
written against 1.1, this is easy, but that's not always the case. I
need to be able to use the correct version of InstallUtil to properly
uninstall the existing Windows Service, which is why I want to detect
the ImageRuntimeVersion of the assembly. After that, I want to be able
to copy the new files to the same directory and install it.

I tried to load it into a separate AppDomain, but I got an error
saying that "Could not load file or assembly...." Here is the code I
did.


AppDomainSetup info = new AppDomainSetup();
info.ApplicationName = "HelloWorld";
info.ApplicationBase =
Path.GetDirectoryName(ServicePath);
info.PrivateBinPath =
Path.GetDirectoryName(ServicePath);

AppDomain ad = AppDomain.CreateDomain("TempAppDomain",
null, info);
Assembly ass = ad.Load(AssemblyByteArray);

string ClrPath =
XCCommon.GetCLRPath(ass.ImageRuntimeVersion);
AppDomain.Unload(ad);

After all, all I want to be able to do is to detect the version of
the .NET Framework that an assembly was compiled against and be able
to delete the assembly.
 
I think I took a wrong direction to solve the problem. After chilling
for a few minutes gave me a different and yet simpler idea.

All I needed was to load an assembly without the upgrade application
holding onto the file. Here is what I did and it seems to work
although I'm not really unloading the assembly from the memory.

byte[] AssemblyByteArray =
System.IO.File.ReadAllBytes(ServicePath);
Assembly ass = Assembly.Load(AssemblyByteArray);
string ClrPath =
XCCommon.GetCLRPath(ass.ImageRuntimeVersion);
ExecutableLauncher.Run(System.IO.Path.Combine(ClrPath,
"InstallUtil.exe"), "/u \"" + ServicePath + "\"");
 
Back
Top