Récupérer par programme le numéro de version d’une DLL

Est-il possible d’obtenir le numéro de version par programmation à partir de n’importe quelle DLL .NET?

Si oui, comment?

Assembly assembly = Assembly.LoadFrom("MyAssembly.dll"); Version ver = assembly.GetName().Version; 

Important: il convient de noter que ce n’est pas la meilleure réponse à la question initiale. N’oubliez pas de lire plus sur cette page.

Cela fonctionne si la DLL est .net ou Win32 . Les méthodes de reflection ne fonctionnent que si la DLL est .net. De plus, si vous utilisez la reflection, le chargement de la dll entière en mémoire est nécessaire. La méthode ci-dessous ne charge pas l’assemblage en mémoire.

 // Get the file version for the notepad. FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll"); // Print the file name and version number. Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' + "Version number: " + myFileVersionInfo.FileVersion); 

De: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx

source primaire

Tout d’abord, vous pouvez être intéressé par deux versions:

  • Version du fichier du système de fichiers Windows, applicable à tous les fichiers exécutables

  • Version d’assemblage incorporée dans un assemblage .NET par le compilateur (évidemment uniquement applicable aux fichiers dll et exe d’assembly .NET)

Dans le premier cas, vous devriez utiliser la réponse de Ben Anderson. dans ce dernier cas, utilisez AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version ou la réponse de Tataro, au cas où l’assembly serait référencé par votre code.

Notez que vous pouvez ignorer toutes les réponses utilisant les .Load() / .LoadFrom() , car celles-ci chargent l’assembly dans l’AppDomain actuel, ce qui est analogue à l’abattage d’une arborescence pour voir son âge.

Pour l’obtenir pour l’assemblage qui a été démarré (winform, application console, etc …)

 using System.Reflection; ... Assembly.GetEntryAssembly().GetName().Version 

Voici un bon moyen d’utiliser un peu de reflection pour obtenir une version d’une DLL contenant une classe particulière:

 var ver = System.Reflection.Assembly.GetAssembly(typeof(!Class!)).GetName().Version; 

Il suffit de remplacer! Class! avec le nom d’une classe définie dans la DLL dont vous souhaitez obtenir la version.

C’est ma méthode préférée car si je déplace les DLL pour différents déploiements, je n’ai pas à modifier le chemin de fichier.

Kris, votre version fonctionne bien lorsque vous devez charger l’assembly à partir du fichier DLL réel (et si la DLL est là!), Cependant, vous obtiendrez une erreur indésirable si la DLL est EMBEDDED (pas un fichier mais un fichier incorporé). DLL).

L’autre chose est que si l’on utilise un système de gestion des versions avec quelque chose comme ” 1.2012.0508.0101 “, quand on obtient la chaîne de version, on obtient réellement ” 1.2012.518.101 “; Notez les zéros manquants .

Voici donc quelques fonctions supplémentaires pour obtenir la version d’une DLL (intégrée ou à partir du fichier DLL):

  public static System.Reflection.Assembly GetAssembly(ssortingng pAssemblyName) { System.Reflection.Assembly tMyAssembly = null; if (ssortingng.IsNullOrEmpty(pAssemblyName)) { return tMyAssembly; } tMyAssembly = GetAssemblyEmbedded(pAssemblyName); if (tMyAssembly == null) { GetAssemblyDLL(pAssemblyName); } return tMyAssembly; }//System.Reflection.Assembly GetAssemblyEmbedded(ssortingng pAssemblyDisplayName) public static System.Reflection.Assembly GetAssemblyEmbedded(ssortingng pAssemblyDisplayName) { System.Reflection.Assembly tMyAssembly = null; if(ssortingng.IsNullOrEmpty(pAssemblyDisplayName)) { return tMyAssembly; } try //try #a { tMyAssembly = System.Reflection.Assembly.Load(pAssemblyDisplayName); }// try #a catch (Exception ex) { ssortingng m = ex.Message; }// try #a return tMyAssembly; }//System.Reflection.Assembly GetAssemblyEmbedded(ssortingng pAssemblyDisplayName) public static System.Reflection.Assembly GetAssemblyDLL(ssortingng pAssemblyNameDLL) { System.Reflection.Assembly tMyAssembly = null; if (ssortingng.IsNullOrEmpty(pAssemblyNameDLL)) { return tMyAssembly; } try //try #a { if (!pAssemblyNameDLL.ToLower().EndsWith(".dll")) { pAssemblyNameDLL += ".dll"; } tMyAssembly = System.Reflection.Assembly.LoadFrom(pAssemblyNameDLL); }// try #a catch (Exception ex) { ssortingng m = ex.Message; }// try #a return tMyAssembly; }//System.Reflection.Assembly GetAssemblyFile(ssortingng pAssemblyNameDLL) public static ssortingng GetVersionSsortingngFromAssembly(ssortingng pAssemblyDisplayName) { ssortingng tVersion = "Unknown"; System.Reflection.Assembly tMyAssembly = null; tMyAssembly = GetAssembly(pAssemblyDisplayName); if (tMyAssembly == null) { return tVersion; } tVersion = GetVersionSsortingng(tMyAssembly.GetName().Version.ToSsortingng()); return tVersion; }//ssortingng GetVersionSsortingngFromAssemblyEmbedded(ssortingng pAssemblyDisplayName) public static ssortingng GetVersionSsortingng(Version pVersion) { ssortingng tVersion = "Unknown"; if (pVersion == null) { return tVersion; } tVersion = GetVersionSsortingng(pVersion.ToSsortingng()); return tVersion; }//ssortingng GetVersionSsortingng(Version pVersion) public static ssortingng GetVersionSsortingng(ssortingng pVersionSsortingng) { ssortingng tVersion = "Unknown"; ssortingng[] aVersion; if (ssortingng.IsNullOrEmpty(pVersionSsortingng)) { return tVersion; } aVersion = pVersionSsortingng.Split('.'); if (aVersion.Length > 0) { tVersion = aVersion[0]; } if (aVersion.Length > 1) { tVersion += "." + aVersion[1]; } if (aVersion.Length > 2) { tVersion += "." + aVersion[2].PadLeft(4, '0'); } if (aVersion.Length > 3) { tVersion += "." + aVersion[3].PadLeft(4, '0'); } return tVersion; }//ssortingng GetVersionSsortingng(Version pVersion) public static ssortingng GetVersionSsortingngFromAssemblyEmbedded(ssortingng pAssemblyDisplayName) { ssortingng tVersion = "Unknown"; System.Reflection.Assembly tMyAssembly = null; tMyAssembly = GetAssemblyEmbedded(pAssemblyDisplayName); if (tMyAssembly == null) { return tVersion; } tVersion = GetVersionSsortingng(tMyAssembly.GetName().Version.ToSsortingng()); return tVersion; }//ssortingng GetVersionSsortingngFromAssemblyEmbedded(ssortingng pAssemblyDisplayName) public static ssortingng GetVersionSsortingngFromAssemblyDLL(ssortingng pAssemblyDisplayName) { ssortingng tVersion = "Unknown"; System.Reflection.Assembly tMyAssembly = null; tMyAssembly = GetAssemblyDLL(pAssemblyDisplayName); if (tMyAssembly == null) { return tVersion; } tVersion = GetVersionSsortingng(tMyAssembly.GetName().Version.ToSsortingng()); return tVersion; }//ssortingng GetVersionSsortingngFromAssemblyEmbedded(ssortingng pAssemblyDisplayName) 
 var versionAtsortingb = new AssemblyName(Assembly.GetExecutingAssembly().FullName); 

Vous pouvez utiliser les méthodes System.Reflection.Assembly.Load * (), puis récupérer leur AssemblyInfo.

Bien que la question d’origine n’ait pas été spécifique à un service Web, voici un testWebService complet que vous pouvez append pour afficher une réponse non mise en cache du service Web plus la version du fichier. Nous utilisons la version de fichier au lieu de la version d’assemblage car nous voulons connaître une version, mais avec toutes les versions d’assemblage 1.0.0.0, le site Web peut être facilement patché (signature et lien de demande toujours actif!). Remplacez @ Class @ par le nom du contrôleur Web Api dans lequel ce service est incorporé. C’est bon pour un go / nogo sur un service Web, plus une vérification rapide de la version.

  [Route("api/testWebService")] [AllowAnonymous] [HttpGet] public HttpResponseMessage TestWebService() { HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK); ssortingng loc = Assembly.GetAssembly(typeof(@Class@)).Location; FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(loc); responseMessage.Content = new SsortingngContent($"

The XXXXX web service GET test succeeded.

{DateTime.Now}

File Version: {versionInfo.FileVersion}"); responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); Request.RegisterForDispose(responseMessage); return responseMessage; }

J’ai également jugé nécessaire d’append ce qui suit à web.config sous configuration pour le rendre véritablement anonyme.