394

I was just wondering how I could automatically increment the build (and version?) of my files using Visual Studio (2005).

If I look up the properties of say C:\Windows\notepad.exe, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not version 1.0.0.0, which let's face it is a bit dull.

I tried a few things, but it doesn't seem to be out-of-box functionality, or maybe I'm just looking in the wrong place (as usual).

I work with mainly web projects....

I looked at both:

  1. http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx
  2. http://www.codeproject.com/KB/dotnet/build_versioning.aspx

and I couldn't believe it so much effort to do something is standard practice.

EDIT: It does not work in VS2005 as far I can tell (http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx)

pb2q
  • 58,613
  • 19
  • 146
  • 147
Ian G
  • 29,468
  • 21
  • 78
  • 92
  • 1
    wild card only seem to work for AssemblyVersion but not for AssemblyFileVersion in VS 2005 – dotnetcoder Dec 31 '08 at 06:32
  • Are there any solutions to this that work for C++ projects in VS2005? All the answers seem to rerlate to .Net. [Related question](http://stackoverflow.com/q/990308/588306). Thanks – Deanna Oct 03 '12 at 09:40
  • 1
    In .Net **Core** projects AssemblyVersion auto-increment doesn't work by default. You need to add  False to csproj. See [Auto Versioning in Visual Studio 2017 (.NET Core)](//stackoverflow.com/a/46985624) – Michael Freidgeim Oct 28 '17 at 04:03

27 Answers27

454

In visual Studio 2008, the following works.

Find the AssemblyInfo.cs file and find these 2 lines:

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

You could try changing this to:

[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]

But this won't give you the desired result, you will end up with a Product Version of 1.0.* and a File Version of 1.0.0.0. Not what you want!

However, if you remove the second of these lines and just have:

[assembly: AssemblyVersion("1.0.*")]

Then the compiler will set the File Version to be equal to the Product Version and you will get your desired result of an automatically increment product and file version which are in sync. E.g. 1.0.3266.92689

Sam Meldrum
  • 13,835
  • 6
  • 33
  • 40
  • 2
    This works as good as anything else, and works in VS2005. I was hoping for some rational number like 1.0.1.56 in lieu I get 1.0.3266.30135 but at least it increases (albeit by some random number :D) – Ian G Dec 10 '08 at 16:46
  • 15
    oh i just read it : it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight) – Ian G Dec 10 '08 at 16:51
  • 23
    Nice call on needing to remove the AssemblyFileVersion attribute to get this to work! – David Faivre Oct 04 '11 at 17:55
  • 84
    I realise this is an old question, but wanted to add this comment for others who find their way to this answer. If you increment the AssemblyVersion, any project that uses your dll will need to be re-compiled. However, if you keep the AssemblyVersion the same and increment the AssemblyFileVersion by itself, then you can swap the new dll in without having to re-compile whatever is using it. So ask yourself this, is this just a new build, or am I releasing a new version? – onefootswill Oct 26 '12 at 02:35
  • 32
    @DD59 the 'Build' is number of days since Jan 1st 2000; the 'Revision' is seconds from midnight *divided* by 2 (not half-seconds, but two-second intervals). See here: http://stackoverflow.com/a/3387167/11545 – Cristian Diaconescu Apr 04 '13 at 08:41
  • @onefootswill but how would you increment the file version separate from the the assembly version if you can only have one of them specified? – Sinaesthetic Nov 20 '14 at 23:20
  • @Sinaesthetic I guess you couldn't iif you can only have one specified. But I've never seen a restriction like that. In the Assembly.cs or the SharedAssemblyInfo.cs (as the case may be), you can always specify both. – onefootswill Nov 21 '14 at 03:30
  • any ideas why this works locally in visual studio, but I seem to be getting `1.0.0.0` in TFS 2010 builds? – Maslow Sep 30 '15 at 02:08
  • How these 3266,92689 two numbers got generated in. `1.0.3266.92689` – Unbreakable Jan 16 '17 at 21:25
  • @Unbreakable 3266 is the number of days since 1-1-2000, 92689 is the amount of two second intervals from midnight. – Justine Krejcha May 15 '17 at 04:56
  • 2
    @JustinKrejcha And yet there are only 86400 seconds in 24 hours... – Ian Sep 06 '17 at 13:52
  • @Ian two-second-intervals. Max would be 43199 at 23:59:59. The Year 3266 would be something in 2008. I guess that Sam chose some random numbers. – kara Jan 16 '18 at 10:52
  • Excellent! This was so useful to me that I blogged it: pretty much the same instructions as above but with some screenshots to demonstrate: http://www.technical-recipes.com/2018/how-to-automatically-increment-build-versions-in-visual-studio/ – AndyUK Sep 24 '18 at 07:44
  • does this no longer work in vs2022? for me.. when i compile my project.. the assemblyinfo.cs file doesn't get updated.. – psj01 Feb 17 '23 at 20:12
157

open up the AssemblyInfo.cs file and change

// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

to

[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]

you can do this in IDE by going to project -> properties -> assembly information

This however will only allow you to auto increment the Assembly version and will give you the

Assembly File Version: A wildcard ("*") is not allowed in this field

message box if you try place a * in the file version field.

So just open up the assemblyinfo.cs and do it manually.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Hath
  • 12,606
  • 7
  • 36
  • 38
  • 1
    Yes I just encountered the ""Assembly File Version: A wildcard ("*") is not allowed in this field" that's what won your method the green tick :D – Ian G Dec 10 '08 at 16:03
  • @in.spite - thats odd i have VS2005 pro and it seems to work the same as vs 2008. – Hath Dec 10 '08 at 16:48
  • 3
    this works: [assembly: AssemblyVersion("1.0.*")] //[assembly: AssemblyFileVersion("1.0.0.0")] – Ian G Dec 10 '08 at 16:49
  • You need to do it in the AssemblyInfo.cs file as discussed. Unfortunately the "Assembly Information" dialog throws an error for our "benefit". Discussion here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=252521 – Topdown Nov 12 '09 at 06:16
  • Also, within the Assembly Information IDE, make sure you either blank out anything smaller than the * in your Assembly version. It tells you you have an "invalid version format" if you don't (e.g., 0 1 * 0 => fail). – patridge Jun 29 '11 at 20:21
  • 4
    It is not desirable to change the AssemblyVersion number during a release cycle. Instead, the AssemblyFileVersion should be changed. See my blog post on this topic: http://philippetruche.wordpress.com/2008/08/12/net-assembly-versioning-lifecycle/ Also see Suzanne Cook's excellent post on when to change the numbers: http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57148.aspx – Philippe Sep 15 '11 at 15:52
  • 62
    I'd be careful using the * it will stop working on June 4th 2179 when the day becomes 65536 – Lloyd Powell Nov 07 '11 at 14:37
  • How can this be achieved in the new _csproj_ format where there is no _AssemblyInfo.cs_? – Shimmy Weitzhandler Oct 10 '17 at 08:07
  • 5
    @Shimmy: Add False to .csproj [Auto Versioning in Visual Studio 2017 (.NET Core)](//stackoverflow.com/a/46985624) – Michael Freidgeim Oct 28 '17 at 04:08
  • 1
    @LloydPowell: MS Excel tells me "June 6th", so at your date you have 2 days left to find a workaround ;-) And don't forget to tell your grandchildren about that issue. – Tobias Knauss Jan 18 '22 at 13:58
  • 1
    @Lloyd Powell, you made my day :D +1 ! – Chris W May 30 '22 at 09:24
  • 1
    @ChrisW I'm glad my 'banter' from 11 years ago is still providing entertainment for the .net community :-) – Lloyd Powell May 31 '22 at 07:32
  • @LloydPowell Yeah, it's kinda timeless. Almost :D – Chris W May 31 '22 at 11:03
56

Another option for changing version numbers in each build is to use the Version task of MSBuild.Community.Tasks. Just download their installer, install it, then adapt the following code and paste it after <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> in your .csproj file:

<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="BeforeBuild">
    <Version VersionFile="Properties\version.txt" Major="1" Minor="0" BuildType="Automatic" StartDate="12/31/2009" RevisionType="BuildIncrement">
      <Output TaskParameter="Major" PropertyName="Major" />
      <Output TaskParameter="Minor" PropertyName="Minor" />
      <Output TaskParameter="Build" PropertyName="Build" />
      <Output TaskParameter="Revision" PropertyName="Revision" />
    </Version>
    <AssemblyInfo CodeLanguage="CS"
                  OutputFile="Properties\VersionInfo.cs"
                  AssemblyVersion="$(Major).$(Minor)"
                  AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" />
</Target>

Note: Adapt the StartDate property to your locale. It currently does not use the invariant culture.

For the third build on January 14th, 2010, this creates a VersionInfo.cs with this content:

[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.14.2")]

This file then has to be added to the project (via Add existing item), and the AssemblyVersion and AssemblyFileVersion lines have to be removed from AssemblyInfo.cs.

The different algorithms for changing the version components are described in $(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.chm and Version Properties.

Christian
  • 9,914
  • 6
  • 45
  • 52
  • 2
    This is the best way yet that I've seen to get around the awful fact that FileVersion structs use 16 bit integers. – Mike Post Mar 25 '12 at 01:55
  • 1
    I had issues installing into VS2012 using the Package Console so recommend using the downloaded nightly msi installers at https://github.com/loresoft/msbuildtasks/downloads. Works copy/paste from the above. Thanks! – DaveO Oct 06 '12 at 12:45
  • After it was denied and edit on this post: "You may also want to check this http://www.loresoft.com/projects/msbuildtasks/sample-build-file-using-msbuild-community-tasks/default.aspx it can improve the basic functionality described before." – radu florescu Oct 27 '12 at 17:29
  • 1
    This is not a viable solution for those who build with TFS. Ultimatey, this will add a pending edit to the VersionInfo.cs and version.txt files. For me, it is not desirable to have a pending edit for each build. – JDennis May 22 '14 at 16:02
  • @JDennis see [here](http://stackoverflow.com/questions/25768653/versioning-net-builds) for TFS versioning tips... – Christian Jan 19 '16 at 17:00
32

I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.

I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,

  <PropertyGroup>
    <Year>$([System.DateTime]::Now.ToString("yy"))</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\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
    </WriteLinesToFile>
  </Target>

This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.

Tohid
  • 6,175
  • 7
  • 51
  • 80
Boog
  • 3,744
  • 4
  • 28
  • 25
  • 1
    Does MSBuild support variables? It would be better to put `[System.DateTime]::Now` into one, otherwise, there's a race condition that can cause an old build number to be used if building near midnight. – Edward Brey Jul 10 '17 at 11:35
  • Did you define these four properties instead of combining them in a single `DateTime.ToString` for demonstrative purposes, or is there a particular reason? – mafu Mar 27 '18 at 14:43
  • If your BeforeBuild event doesn't fire in VS2017 check out https://stackoverflow.com/questions/43921992/how-can-i-use-beforebuild-and-afterbuild-targets-with-visual-studio-2017 – Rhys Jones May 01 '19 at 11:03
  • This solution is the best fit out of all the answers here. However, the problem is, the timestamp (or the content of the versioninfo.cs file) does not update if you build the project for the second time which should produce a different minute. If I close and reload the project, then the timestamp gets updated. Is this a bug from MSBuild? @Boog – Cary May 07 '19 at 15:15
  • Is this possible to make any operation in these markups? With `$([System.DateTime]::Today.Year - 2010)`, I get an error _unable to evaluate expression ""24/08/2020 00:00:00".Year - 2010". Cannot find method 'SystemDateTime.Year -2009'._ – sinsedrix Aug 24 '20 at 11:59
  • 2
    That's an excellent solution for someone who wants to follow [calver](https://calver.org)! +1 from me. One thing I would simplify is the variables: `$([System.DateTime]::Now.ToString("yyyy.M.d.HHmm"))`. Works like a charm. – Stelios Adamantidis Mar 21 '21 at 17:39
18

There is a visual studio extension Automatic Versions which supports Visual Studio (2017,2019 & 2022)

Screen Shots enter image description here

enter image description here

Rahul
  • 2,431
  • 3
  • 35
  • 77
  • So I have uninstalled it and I can say even more... it modifies original csproj file. I think it is very problematic extension. – Maxim Apr 07 '17 at 23:15
  • 3
    @Maxim Try latest version, it should work on VS 2017 – Rady Apr 16 '17 at 09:49
  • Excellent util. Works fine for me in vs2017. Docs could be slightly clearer, but install it (via the site) and then install MSBuild via Nuget, apply to a small project and play and build. Nice. @Boog's answer didn't work for me although he said exactly what I was trying to achieve. – err1 Nov 25 '19 at 15:37
  • 1
    Yes! I love this product!! – Missy Jun 30 '21 at 16:59
  • VS2022 supported! – obnews Sep 27 '22 at 23:26
17

Install the Build Version Increment add-in. It gives you way more control than the * option.

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
  • Only for VS2005/2008, with a beta for VS2010 – SteveC Jun 06 '14 at 09:33
  • https://autobuildversion.codeplex.com/discussions/393154 The DropBox link near the end of the thread, from r3mote203, is for 2010 and works in 2012 (and maybe 2013). – Grault Sep 29 '14 at 18:51
  • 2
    I'm using [Automatic Versions](https://visualstudiogallery.msdn.microsoft.com/dd8c5682-58a4-4c13-a0b4-9eadaba919fe) for VS2012, and it's working very well. – redcurry Jul 20 '15 at 21:35
13

To get the version numbers try

 System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
 System.Reflection.AssemblyName assemblyName = assembly.GetName();
 Version version = assemblyName.Version;

To set the version number, create/edit AssemblyInfo.cs

 [assembly: AssemblyVersion("1.0.*")]
 [assembly: AssemblyFileVersion("1.0.*")]

Also as a side note, the third number is the number of days since 2/1/2000 and the fourth number is half of the amount of total seconds in the day. So if you compile at midnight it should be zero.

NoWar
  • 36,338
  • 80
  • 323
  • 498
Bob
  • 97,670
  • 29
  • 122
  • 130
10

In Visual Studio 2019

It was not enough for me adding

[assembly: AssemblyVersion("1.0.*")]

When building it throws me this error

The specified version string does not conform to the required format

Solution

The format was finally accepted after I set Deterministic to False in project.csproj

<Deterministic>false</Deterministic>

Edit:

For some reason setting Deterministic to False messed up my config file loading it and saving it on different locations.

Workaround:

I setup a post-build event to increment the revision number:

Post-Build Event batch script

This calls a powershell script named autoincrement_version.ps1 passing as argument the path of AssemblyInfo.cs

if $(ConfigurationName) == Release (
PowerShell -ExecutionPolicy RemoteSigned $(ProjectDir)autoincrement_version.ps1 '$(ProjectDir)My Project\AssemblyInfo.cs'
)

Poweshell script

It autoincrements the revision number using Regex

param( [string]$file );
  $regex_revision = '(?<=Version\("(?:\d+\.)+)(\d+)(?="\))'
  $found = (Get-Content $file) | Select-String -Pattern $regex_revision
  $revision = $found.matches[0].value
  $new_revision = [int]$revision + 1
  (Get-Content $file) -replace $regex_revision, $new_revision | Set-Content $file -Encoding UTF8
Community
  • 1
  • 1
Madacol
  • 3,611
  • 34
  • 33
8

Setting a * in the version number in AssemblyInfo or under project properties as described in the other posts does not work with all versions of Visual Studio / .NET.

Afaik it did not work in VS 2005 (but in VS 2003 and VS 2008). For VS 2005 you could use the following: Auto Increment Visual Studio 2005 version build and revision number on compile time.

But be aware that changing the version number automatically is not recommended for strong-named assemblies. The reason is that all references to such an assembly must be updated each time the referenced assembly is rebuilt due to the fact that strong-named assembly references are always a reference to a specific assembly version. Microsoft themselves change the version number of the .NET Framework assemblies only if there are changes in interfaces. (NB: I'm still searching for the link in MSDN where I read that.)

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • I think for any version of VS you can only put the * in the Build or Revision boxes. I just tried this out using VS 2005, and it works fine. I'm not sure what the author of that code project article is talking about. – MusiGenesis Dec 10 '08 at 16:03
  • Maybe it came back with a service pack, but I remember that it did not use to work when I was using VS 2005. – Dirk Vollmar Dec 10 '08 at 16:11
  • It does not work with 2005, I'll look for a service pack and report back. – Ian G Dec 10 '08 at 16:14
  • Maybe MusiGenesis has an add-on installed which is enabling automatic versioning. – Dirk Vollmar Dec 10 '08 at 16:21
  • @divo: no, I'm add-on-phobic. I just have Visual Studio 2005 Professional SP1. I've never seen a problem with the *, but I usually increment manually. Sounds like a weird bug. – MusiGenesis Dec 10 '08 at 18:23
  • @0xA3 I believe the MSDN link you are referring to is http://support.microsoft.com/kb/556041 – Xcalibur Apr 20 '12 at 02:38
6

To get incrementing (DateTime) information into the AssemblyFileVersion property which has the advantage of not breaking any dependencies.


Building on Boog's solution (did not work for me, maybe because of VS2008?), you can use a combination of a pre-build event generating a file, adding that file (including its version properties) and then using a way to read out those values again. That is..

Pre-Build-Event:

echo [assembly:System.Reflection.AssemblyFileVersion("%date:~-4,4%.%date:~-7,2%%date:~-10,2%.%time:~0,2%%time:~3,2%.%time:~-5,2%")] > $(ProjectDir)Properties\VersionInfo.cs

Include the resulting VersionInfo.cs file (Properties subfolder) into your project

Code to get Date back (years down to seconds):

var version = assembly.GetName().Version;
var fileVersionString = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
Version fileVersion = new Version(fileVersionString);
var buildDateTime = new DateTime(fileVersion.Major, fileVersion.Minor/100, fileVersion.Minor%100, fileVersion.Build/100, fileVersion.Build%100, fileVersion.Revision);

Not very comfortable.. also, I do not know if it creates a lot of force-rebuilds (since a file always changes).

You could make it smarter for example if you only update the VersionInfo.cs file every few minutes/hours (by using a temporary file and then copying/overwriting the real VersionInfo.cs if a change large enough is detected). I did this once pretty successfully.

Andreas Reiff
  • 7,961
  • 10
  • 50
  • 104
  • It works perfectly. However, this regular expression %date:~-4,4%.%date:~-7,2%%date:~-10,2%.%time:~0,2%%time:~3,2%.%time:~-5,2%" is just too complicated. – Cary May 07 '19 at 12:43
5

Set the version number to "1.0.*" and it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight)

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • hey if I had read this properly at the beginning I would have saved myself mucho agro. thx – Ian G Dec 10 '08 at 16:50
5

It is in your project properties under Publish

http://screencast.com/t/Vj7rhqJO
(~ http://screencast.com/t/Vj7rhqJO)

Community
  • 1
  • 1
Alex
  • 12,749
  • 3
  • 31
  • 45
5

How to get the version {major}.{year}.1{date}.1{time}

This one is kind of experimental, but I like it. Inspired by Jeff Atwood @ CodingHorror (link).

The resulting version number becomes 1.2016.10709.11641 (meaning 2016-07-09 16:41), which allows for

  • poor mans zero padding (with the stupid leading 1s)
  • nearly-human readable local DateTime embedded into the version number
  • leaving Major version alone for really major breaking changes.

Add a new item to your project, select General -> Text Template, name it something like CustomVersionNumber and (where applicable) comment out the AssemblyVersion and AssemblyFileVersion in Properties/AssemblyInfo.cs.

Then, when saving this file, or building the project, this will regenerate a .cs file located as a sub-item under the created .tt file.

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>

//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//

using System.Reflection;

<#
    var date = DateTime.Now;
    int major = 1;
    int minor = date.Year;
    int build = 10000 + int.Parse(date.ToString("MMdd"));
    int revision = 10000 + int.Parse(date.ToString("HHmm"));
#>

[assembly: AssemblyVersion("<#= $"{major}.{minor}.{build}.{revision}" #>")]
[assembly: AssemblyFileVersion("<#= $"{major}.{minor}.{build}.{revision}" #>")]
  • You are not compiling your program every minute or deploying more than once a day, so technically the time part is unnecessarily occupying valuable information, I would use 1st and 2nd for major minor and and just use 3rd number for date yyddd (two digit year + ddd day from start of same year) and leave 4th for incremental build number. – AaA Mar 12 '18 at 01:56
4

Cake supports AssemblyInfo files patching. With cake in hands you have infinite ways to implement automatic version incrementing.

Simple example of incrementing version like C# compiler does:

Setup(() =>
{
    // Executed BEFORE the first task.
    var datetimeNow = DateTime.Now;
    var daysPart = (datetimeNow - new DateTime(2000, 1, 1)).Days;
    var secondsPart = (long)datetimeNow.TimeOfDay.TotalSeconds/2;
    var assemblyInfo = new AssemblyInfoSettings
    {
        Version = "3.0.0.0",
        FileVersion = string.Format("3.0.{0}.{1}", daysPart, secondsPart)
    };
    CreateAssemblyInfo("MyProject/Properties/AssemblyInfo.cs", assemblyInfo);
});

Here:

  • Version - is assembly version. Best practice is to lock major version number and leave remaining with zeroes (like "1.0.0.0").
  • FileVersion - is assembly file version.

Note that you can patch not only versions but also all other necessary information.

hal
  • 1,705
  • 1
  • 22
  • 28
3

Go to Project | Properties and then Assembly Information and then Assembly Version and put an * in the last or the second-to-last box (you can't auto-increment the Major or Minor components).

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
2

Maybe, for this task, you can use code like this:

    private bool IncreaseFileVersionBuild()
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            try
            {
                var fi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.GetDirectories("Properties")[0].GetFiles("AssemblyInfo.cs")[0];
                var ve = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string ol = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + ve.FileBuildPart.ToString() + "." + ve.FilePrivatePart.ToString();
                string ne = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + (ve.FileBuildPart + 1).ToString() + "." + ve.FilePrivatePart.ToString();
                System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace("[assembly: AssemblyFileVersion(\"" + ol + "\")]", "[assembly: AssemblyFileVersion(\"" + ne + "\")]"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        return false;
    }

and call it from form loading.
With this code you can update any part of file info in AssemblyInfo.cs (but you must use "standard" directory structure).

Atiris
  • 2,613
  • 2
  • 28
  • 42
2

Changing the AssemblyInfo works in VS2012. It seems strange that there's not more support for this in Visual Studio, you'd think this was a basic part of the build/release process.

Maxcelcat
  • 151
  • 3
2

As of right now, for my application,

string ver = Application.ProductVersion;

returns ver = 1.0.3251.27860

The value 3251 is the number of days since 1/1/2000. I use it to put a version creation date on the splash screen of my application. When dealing with a user, I can ask the creation date which is easier to communicate than some long number.

(I'm a one-man dept supporting a small company. This approach may not work for you.)

Deanna
  • 23,876
  • 7
  • 71
  • 156
SeaDrive
  • 4,182
  • 5
  • 32
  • 30
  • Your number is gonna run out fast. I would use yyddd which is 2 digit year and 3 digit day from start of year which is max 365. at least your program would compile until year 2065. then you would be retired and let someone else figure out how they want to handle it. given your program is still in commission at that date! – AaA Mar 12 '18 at 01:52
2

Use the AssemblyInfo task from the MSBuild Community Tasks (http://msbuildtasks.tigris.org/) project, and integrate it into your .csproj/.vbproj file.

It has a number of options, including one to tie the version number to the date and time of day.

Recommended.

devstuff
  • 8,277
  • 1
  • 27
  • 33
2

I have created an application to increment the file version automatically.

  1. Download Application
  2. add the following line to pre-build event command line

    C:\temp\IncrementFileVersion.exe $(SolutionDir)\Properties\AssemblyInfo.cs

  3. Build the project

To keep it simple the app only throws messages if there is an error, to confirm it worked fine you will need to check the file version in 'Assembly Information'

Note : You will have to reload the solution in Visual studio for 'Assembly Information' button to populate the fields, however your output file will have the updated version.

For suggestions and requests please email me at telson_alva@yahoo.com

Telson Alva
  • 842
  • 6
  • 22
  • 37
1

AssemblyInfoUtil. Free. Open-source.

Sergiy
  • 1,912
  • 2
  • 16
  • 25
1

I'm using this approach https://stackoverflow.com/a/827209/3975786 by placing the T4 template in a "Solution Items" and using it with "Add as Link" within each project.

Community
  • 1
  • 1
mcandal
  • 407
  • 4
  • 10
1

Maybe it's too late to answer here but hope that will solve someone's hectic problem.

An automatic way to change assembly version of all of your projects using PowerShell script. This article will solve many of your problems.

Khawaja Asim
  • 1,327
  • 18
  • 38
  • 1
    The only problem with PS is it is slow to react and requires configuration to allow it to run. I would go with a small executable, a tt4 file or even inline code which I think any programmer can write in one way. – AaA Mar 12 '18 at 01:59
1

I tried this with Visual Studio 2019 and it did not work. In newer versions of VS at least the Deterministic-flag prevents the auto-update. But changing the 14th line of Your-project-name.csproj to <Deterministic>false</Deterministic> and changing the version number string to "1.0.*" did not help me.

So I made a litle vbs script that does the job. it changes the version number to (Major version).(Minor version).([year][dayofyear]).(increment).

Copy the script into a folder and put the following into pre-compile build-commandline:

"Path-to-this-script\UpdateVersion.vbs"  "$(ProjectDir)"

(including the quotes and filling in the real path of Your machine) and You are done.

Get it here: https://github.com/abtzero/VS_UpdateVersion.git

Abtzero
  • 19
  • 4
0

Each time I do a build it auto-increments the least-significant digit.

I don't have any idea how to update the others, but you should at least be seeing that already...

Brian Knoblauch
  • 20,639
  • 15
  • 57
  • 92
  • 1
    The VS is in charge of incrementing the last number which is usually the build number. Everything else (i.e. the numbers before that) is up to you because they represent the version of your application. – Огњен Шобајић Sep 25 '14 at 19:55
  • 1
    Огњен Шобајић: Not quite right. Microsoft's numbering scheme is major.minor.build.revision, eg 1.0.4.7. If you set the assembly version to something like "1.0.*" then VS will set the build and revision numbers for you. In that case build will increment daily, and revision will be the number of seconds since midnight, divided by 2. – Simon Elms May 17 '16 at 10:46
0

For anyone using Tortoise Subversion, you can tie one of your version numbers to the subversion Revision number of your source code. I find this very useful (Auditors really like this too!). You do this by calling the WCREV utility in your pre-build and generating your AssemblyInfo.cs from a template.

If your template is called AssemblyInfo.wcrev and sits in the normal AssemblyInfo.cs directory, and tortoise is in the default installation directory, then your Pre-Build command looks like this (N.B. All on one line):

"C:\Program Files\TortoiseSVN\bin\SubWCRev.exe" "$(ProjectDir)." "$(ProjectDir)Properties\AssemblyInfo.wcrev"  "$(ProjectDir)Properties\AssemblyInfo.cs"

The template file would include the wcrev token substitution string: $WCREV$
e.g.

[assembly: AssemblyFileVersion("1.0.0.$WCREV$")]

Note:
As your AssemblyInfo.cs is now generated you do not want it version controled.

0

If you are using Git + TortoiseGit there are very easy way to update AssemblyInfo.cs and update values of AssemblyVersion and AssemblyFileVersion with number of git commits count.

  1. Copy your AssemblyInfo.cs and name it AssemblyInfo.template
  2. Comment out lines below in AssemblyInfo.cs:
//[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")]</pre>
  1. Change these lines in your AssemblyInfo.template file as:
[assembly: AssemblyVersion("1.0.1.$WCLOGCOUNT$")]
[assembly: AssemblyFileVersion("1.0.1.$WCLOGCOUNT$")]
  1. Add this line to your project's prebiuld events:
GitWCRev "$(ProjectDir)\" "$(ProjectDir)Properties\AssemblyInfo.template" "$(ProjectDir)Properties\AssemblyInfo.cs"

Screenshot of Build Events

Now, (even if you are building on Debug Configuration) your AssemblyInfo.cs will be generated like this:

[assembly: AssemblyVersion("1.0.1.444")]
[assembly: AssemblyFileVersion("1.0.1.444")]

And you are ready.

CoolWolf
  • 19
  • 5