- Assembly Name. Version Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Assembly versioning
- Version information
- Assembly version number
- Assembly informational version
- Use AssemblyVersion and AssemblyFileVersion attributes
- Summary
- AssemblyVersion
- AssemblyFileVersion
- Attributes in AssemblyInfo.cs
- Управление версиями сборок Assembly versioning
- Сведения о версии Version information
- Номер версии сборки Assembly version number
- Информационная версия сборки Assembly informational version
Assembly Name. Version Свойство
Определение
Возвращает или задает для сборки основной номер версии, промежуточный номер версии, номер построения и номер редакции. Gets or sets the major, minor, build, and revision numbers of the assembly.
Значение свойства
Объект, предоставляющий для сборки основной номер версии, промежуточный номер версии, номер построения и номер редакции. An object that represents the major, minor, build, and revision numbers of the assembly.
Примеры
Этот раздел содержит два примера. This section contains two examples. В первом примере показано, как получить версию выполняемой в данный момент сборки. The first example shows how to retrieve the version of the currently executing assembly. Во втором примере показано, как использовать Version свойство для указания версии сборки при выпуске динамической сборки. The second example shows how to use the Version property to specify the assembly version when you emit a dynamic assembly.
Пример 1 Example 1
В следующем примере извлекаются и отображаются номера версий выполняющейся сборки и сборки, содержащей String класс. The following example retrieves and displays the version numbers of the currently executing assembly and the assembly that contains the String class.
Пример 2 Example 2
Следующий пример создает динамическую сборку и сохраняет ее в текущем каталоге. The following example emits a dynamic assembly and saves it to the current directory. При создании сборки Version свойство используется для указания сведений о версии для сборки. When the assembly is created, the Version property is used to specify version information for the assembly.
Комментарии
Все компоненты версии должны быть целыми числами больше или равными нулю. All components of the version must be integers greater than or equal to zero. Метаданные ограничивают основной, дополнительный, номер сборки и компоненты редакции для сборки максимальным значением UInt16.MaxValue -1. Metadata restricts the major, minor, build, and revision components for an assembly to a maximum value of UInt16.MaxValue — 1. Если компонент превышает это значение, ошибка не возникает; Однако в динамической сборке этот компонент равен нулю. If a component exceeds this value, no error is thrown; however, in a dynamic assembly, that component is zero.
Assembly versioning
All versioning of assemblies that use the common language runtime is done at the assembly level. The specific version of an assembly and the versions of dependent assemblies are recorded in the assembly’s manifest. The default version policy for the runtime is that applications run only with the versions they were built and tested with, unless overridden by explicit version policy in configuration files (the application configuration file, the publisher policy file, and the computer’s administrator configuration file).
Versioning is done only on assemblies with strong names.
The runtime performs several steps to resolve an assembly binding request:
Checks the original assembly reference to determine the version of the assembly to be bound.
Checks for all applicable configuration files to apply version policy.
Determines the correct assembly from the original assembly reference and any redirection specified in the configuration files, and determines the version that should be bound to the calling assembly.
Checks the global assembly cache, codebases specified in configuration files, and then checks the application’s directory and subdirectories using the probing rules explained in How the runtime locates assemblies.
The following illustration shows these steps:
For more information about configuring applications, see Configure apps. For more information about binding policy, see How the runtime locates assemblies.
Version information
Each assembly has two distinct ways of expressing version information:
The assembly’s version number, which, together with the assembly name and culture information, is part of the assembly’s identity. This number is used by the runtime to enforce version policy and plays a key part in the type resolution process at run time.
An informational version, which is a string that represents additional version information included for informational purposes only.
Assembly version number
Each assembly has a version number as part of its identity. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. This version number is physically represented as a four-part string with the following format:
For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build number, and 0 as the revision number.
The version number is stored in the assembly manifest along with other identity information, including the assembly name and public key, as well as information on relationships and identities of other assemblies connected with the application.
When an assembly is built, the development tool records dependency information for each assembly that is referenced in the assembly manifest. The runtime uses these version numbers, in conjunction with configuration information set by an administrator, an application, or a publisher, to load the proper version of a referenced assembly.
The runtime distinguishes between regular and strong-named assemblies for the purposes of versioning. Version checking only occurs with strong-named assemblies.
For information about specifying version binding policies, see Configure apps. For information about how the runtime uses version information to find a particular assembly, see How the runtime locates assemblies.
Assembly informational version
The informational version is a string that attaches additional version information to an assembly for informational purposes only; this information is not used at run time. The text-based informational version corresponds to the product’s marketing literature, packaging, or product name and is not used by the runtime. For example, an informational version could be «Common Language Runtime version 1.0» or «NET Control SP 2». On the Version tab of the file properties dialog in Microsoft Windows, this information appears in the item «Product Version».
Although you can specify any text, a warning message appears on compilation if the string is not in the format used by the assembly version number, or if it is in that format but contains wildcards. This warning is harmless.
Use AssemblyVersion and AssemblyFileVersion attributes
This article introduces how to use AssemblyVersion and AssemblyFileVersion attributes in the AssemblyInfo.cs file.
Original product version: В .NET Framework
Original KB number: В 556041
Summary
AssemblyInfo.cs provides two attributes to set two different types of versions. This tip shows how to use those two attributes.
Microsoft .NET framework provides opportunity to set two different types of version numbers to each assembly.
AssemblyVersion
It’s the version number used by framework during build and at runtime to locate, link, and load the assemblies. When you add reference to any assembly in your project, it’s this version number that gets embedded. At runtime, Common Language Runtime (CLR) looks for assembly with this version number to load. But remember this version is used along with name, public key token and culture information only if the assemblies are strong-named signed. If assemblies aren’t strong-named signed, only file names are used for loading.
AssemblyFileVersion
It’s the version number given to file as in file system. It’s displayed by Windows Explorer, and never used by .NET framework or runtime for referencing.
Attributes in AssemblyInfo.cs
Providing a (*) in place of absolute number makes compiler increase the number by one every time you build.
Suppose you’re building a framework assembly for your project that is used by lot of developers while building the application assemblies. If you release new version of assembly frequently, say once every day, and if assemblies are strong named, Developers will have to change the reference every time you release new assembly. It can be cumbersome and may lead to wrong references also. A better option in such closed group and volatile scenarios would be to fix the AssemblyVersion and change only the AssemblyFileVersion . Use the assembly file version number to communicate the latest release of assembly. In this case, developers won’t have to change the references and they can overwrite the assembly in reference path. In central or final release builds it makes more sense to change the AssemblyVersion and most keep the AssemblyFileVersion same as assembly version.
Управление версиями сборок Assembly versioning
Управление версиями сборок, использующих среду CLR, производится полностью на уровне сборки. All versioning of assemblies that use the common language runtime is done at the assembly level. Конкретная версия сборки и версии зависимых от нее сборок указываются в манифесте сборки. The specific version of an assembly and the versions of dependent assemblies are recorded in the assembly’s manifest. Политика управления версиями по умолчанию для среды выполнения заключается в том, что приложения могут выполняться только с версиями, с которыми они были разработаны и протестированы, если иное не переопределено явной политикой использования версий в файлах конфигурации (в файле конфигурации приложения, файле политики издателя и файле конфигурации администратора компьютера). The default version policy for the runtime is that applications run only with the versions they were built and tested with, unless overridden by explicit version policy in configuration files (the application configuration file, the publisher policy file, and the computer’s administrator configuration file).
Управление версиями выполняется только для сборок со строгими именами. Versioning is done only on assemblies with strong names.
Среда выполнения предпринимает несколько шагов для разрешения запроса привязки сборок. The runtime performs several steps to resolve an assembly binding request:
Проверяет исходную ссылку на сборку для определения версии сборки, с которой будет связано приложение. Checks the original assembly reference to determine the version of the assembly to be bound.
Проверяет все применимые файлы конфигурации для использования политики управления версиями. Checks for all applicable configuration files to apply version policy.
Определяет правильную сборку на основании исходной ссылки на сборку и любого указанного в файлах конфигурации перенаправления, а также версию, которая должна связываться с вызывающей сборкой. Determines the correct assembly from the original assembly reference and any redirection specified in the configuration files, and determines the version that should be bound to the calling assembly.
Проверяет глобальный кэш сборок и указанные в файлах конфигурации базы кода, а затем проверяет папку приложения и вложенные папки с помощью правил проверки, описанных в разделе Обнаружение сборок в среде выполнения. Checks the global assembly cache, codebases specified in configuration files, and then checks the application’s directory and subdirectories using the probing rules explained in How the runtime locates assemblies.
Указанные шаги показаны на следующей иллюстрации: The following illustration shows these steps:
Дополнительные сведения о настройке приложений см. в разделе Настройка приложений. For more information about configuring applications, see Configure apps. Дополнительные сведения о политике привязки см. в разделе Обнаружение сборок в среде выполнения. For more information about binding policy, see How the runtime locates assemblies.
Сведения о версии Version information
В каждой сборке есть два различных способа задания сведений о версии. Each assembly has two distinct ways of expressing version information:
Номер версии сборки, который наряду с именем сборки и сведениями о языке и региональных параметрах является частью удостоверения сборки. The assembly’s version number, which, together with the assembly name and culture information, is part of the assembly’s identity. Это номер используется средой выполнения для применения политики управления версиями и играет ключевую роль в процессе разрешения типов на этапе выполнения. This number is used by the runtime to enforce version policy and plays a key part in the type resolution process at run time.
Информационная версия, которая представляет собой строку с дополнительными сведениями о версии, служащую исключительно в информационных целях. An informational version, which is a string that represents additional version information included for informational purposes only.
Номер версии сборки Assembly version number
Каждая сборка имеет номер версии, являющийся частью ее удостоверения. Each assembly has a version number as part of its identity. Следовательно, две сборки, имеющие разные номера версий, рассматриваются средой выполнения как совершенно разные сборки. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. Этот номер версии физически представляется в виде строки из четырех частей следующего формата: This version number is physically represented as a four-part string with the following format:
Например, в версии «1.5.1254.0» число «1» представляет основную версию, «5» — младший номер версии, «1254» — номер построения, а «0» — номер редакции. For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build number, and 0 as the revision number.
Номер версии сохраняется в манифесте сборки вместе с другими данными удостоверения, включая имя сборки и открытый ключ, а также сведения о связях и удостоверениях других подключаемых к приложению сборок. The version number is stored in the assembly manifest along with other identity information, including the assembly name and public key, as well as information on relationships and identities of other assemblies connected with the application.
При построении сборки средство разработки записывает сведения о зависимостях каждой сборки, на которую имеется ссылка, в манифест сборки. When an assembly is built, the development tool records dependency information for each assembly that is referenced in the assembly manifest. Среда выполнения использует эти номера версий вместе с конфигурационными данными, установленными администратором, приложением или издателем для загрузки нужной версии сборки, на которую имеется ссылка. The runtime uses these version numbers, in conjunction with configuration information set by an administrator, an application, or a publisher, to load the proper version of a referenced assembly.
С целью управления версиями среда выполнения разделяет обычные сборки и сборки со строгими именами. The runtime distinguishes between regular and strong-named assemblies for the purposes of versioning. Проверка версий производится только для сборок со строгими именами. Version checking only occurs with strong-named assemblies.
Сведения о политиках привязки версий см. в разделе Настройка приложений. For information about specifying version binding policies, see Configure apps. Дополнительные сведения о способе использования средой выполнения сведений о версии для поиска определенной сборки см. в разделе Обнаружение сборок в среде выполнения. For information about how the runtime uses version information to find a particular assembly, see How the runtime locates assemblies.
Информационная версия сборки Assembly informational version
Информационная версия сборки представляет собой строку, которая добавляет к сборке дополнительные данные и служит только для информации. Она не используется на этапе выполнения. The informational version is a string that attaches additional version information to an assembly for informational purposes only; this information is not used at run time. Информационная версия (в текстовом формате) соответствует описанию продукта на рынке, данным о комплектации или названии продукта. Эта версия не используется средой выполнения. The text-based informational version corresponds to the product’s marketing literature, packaging, or product name and is not used by the runtime. Так, информационная версия может быть задана как «Среда CLR версии 1.0» или «Элемент управления NET с пакетом обновления 2». For example, an informational version could be «Common Language Runtime version 1.0» or «NET Control SP 2». В Microsoft Windows эта информация отображается в элементе «Версия продукта» на вкладке «Версии» в диалоговом окне свойств файла. On the Version tab of the file properties dialog in Microsoft Windows, this information appears in the item «Product Version».
Хотя можно задать любой текст, при компиляции появится предупреждение, если строка имеет формат отличный от формата номера версии сборки или если она имеет правильный формат, но содержит подстановочные знаки. Although you can specify any text, a warning message appears on compilation if the string is not in the format used by the assembly version number, or if it is in that format but contains wildcards. Это не опасное предупреждение. This warning is harmless.