Skip to content
June 7, 2013 / windperson

利用MSBuild在Visual Studio建置專案時自動寫入檔案版本號碼(AssemblyFileVersion)

  1. Visual Studio專案檔(.csproj)用文字編輯器打開,增加一行
    <Import Project="MakeVersion.targets" Condition="exists('MakeVersion.targets')" />
    

    在專案檔的最後面提供用來撰寫MSBuild的位置,如下圖
    AddTargetReference

  2. 儲存修改的結果後,如果此時Visual Studio有打開該專案的話,會提示一個檔案變更的對話視窗,選擇[重新載入]:
    ReloadProjectFile
  3. 建立一個叫做MakeVersion.targets的MSBuild script檔案,內容如下:
    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <ItemGroup>
        <Compile Include="Properties\BuildIncrementVersionInfo.cs" />
      </ItemGroup>
      <PropertyGroup>
        <Year>$([System.DateTime]::Now.ToString("yyyy"))</Year>
        <Month>$([System.DateTime]::Now.ToString("MM"))</Month>
        <Date>$([System.DateTime]::Now.ToString("dd"))</Date>
        <Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
        <AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
      </PropertyGroup>
      <Target Name="BeforeBuild">
        <WriteLinesToFile File="Properties\BuildIncrementVersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
        </WriteLinesToFile>
      </Target>
    </Project>
    
  4. MakeVersion.targets檔案加入至專案中,如圖:
    AddTargetFile
  5. 修改此專案中Properties目錄下的AssemblyInfo.cs這個檔案,將最後一行的AssemblyFileVersion改為AssemblyInformationalVersion
    VisualStudio_EditAssemblyInfo
  6. 之後用Visual Studio建置該專案時,會將該專案當時的編譯時間(YYYY . MM . DD . HHmm的格式,YYYY:西元年、MM:月、DD:日、HH:24進位制小時、mm:分鐘)輸出至的二進位檔(.exe和 .dll)的檔案版本(AssemblyFileVersion)內,在檔案總管內對該檔案按右鍵看內容就可以看到:
    CheckFileVersion

Reference:

  1. MSBuild Script:
    http://stackoverflow.com/a/6472195
  2. .Net Versioning:
    http://techblog.ranjanbanerji.com/post/2008/06/26/net-assembly-vs-file-versions.aspx
    http://support.microsoft.com/kb/556041
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: