[ Automatically Increment an Application's Build Number in C#.NET ]

By: Daniel S. Soper


The source code below demonstrates how to automatically increment the build number of an application written in C#.NET. This example applies to Visual Studio 2005 using version 2.0 of the .NET framework, but can be easily modified for other environments.

In the Visual Studio 2005 implementation of C#, the application build number is by default stored within the 'AssemblyInfo.cs' file, which resides within the application's 'Properties' folder. The source code below works by finding the build number within this file, incrementing the build number, and then rewriting the file.

Here's the C# source code... Only 37 lines (including comments)!

/// 
/// This code automatically increments an application's build number.
/// USAGE: Paste the static 'IncrementBuild()' method into your
///        application's 'Program' class, and call it from within the
///        'Main()' method.
/// IMPORTANT: The 'IncrementBuild()' method requires the 'System.IO'
///            namespace! e.g. 'using System.IO;'
/// ******************************************************************
///  AUTHOR: Daniel S. Soper
///     URL: http://www.danielsoper.com
///    DATE: 22 December 2007
/// LICENSE: Public Domain. Enjoy!   :-)
/// ******************************************************************
/// 
private static void IncrementBuild()
{ //increments the application's build number
    FileInfo fi = new FileInfo(Application.StartupPath.Substring(0, Application.StartupPath.Length - 9) + "Properties\\AssemblyInfo.cs");

    if (fi.Exists)
    { //if the AssemblyInfo.cs file was found
        StreamReader sr = new StreamReader(fi.FullName);
        string fileContent = sr.ReadToEnd();
        sr.Close();
        int find = fileContent.IndexOf("[assembly: AssemblyVersion");
        for (int i = 0; i < 2; i++) find = fileContent.IndexOf(".", find) + 1;
        int find2 = fileContent.IndexOf(".", find);
        int build = Convert.ToInt32(fileContent.Substring(find, find2 - find)) + 1;
        fileContent = fileContent.Substring(0, find) + build.ToString() + fileContent.Substring(find2);
        find = fileContent.IndexOf("[assembly: AssemblyFileVersion");
        for (int i = 0; i < 2; i++) find = fileContent.IndexOf(".", find) + 1;
        find2 = fileContent.IndexOf(".", find);
        fileContent = fileContent.Substring(0, find) + build.ToString() + fileContent.Substring(find2);
        StreamWriter sw = new StreamWriter(fi.FullName);
        sw.Write(fileContent);
        sw.Close();
    } //end if
} //end IncrementBuild method
			

Click here to return to the Free Programming Resources index

Click here to return to DanielSoper.com