Reading the Version number from a AssemblyInfo.cs file

AssemblyInfo.cs file gets compiled to IL assembly.

If you load that assembly you can read the version with all the examples that you have already seen. Which is reading an embedded version information from a compiled assembly file, and it may be overwritten by compilation process to a value different from what is in AssemblyInfo.cs

However it sounds like what you want instead is to read a version number from AssemblyInfo.cs text file, without compiling it down.

If this is the case you really just have to use regex with a format appropriate for your project, or even come up with a convention that will keep it simple.

This could be as simple as

var versionMatch = Regex.Match(File.ReadAllText(filename), @"AssemblyVersion\s*\(\s*""([0-9\.\*]*?)""\s*\)");
if (versionMatch.Success)
{
    Console.WriteLine(versionMatch.Groups[1].Value);
}

You would have to consider convention around what goes there, since 1.0.* is a valid version string that translates to timestamp values of form 1.0.nnn.mmm at compile time, and nnn and mmm part closely guessable but not precisely guessable.


You can specify the target assembly path in AssemblyName.GetAssemblyName

AssemblyName.GetAssemblyName("ProjectB.exe").Version

You can get Assembly version without loading it as:

using System.Reflection;
using System.IO;

...

// Get assembly 
AssemblyName currentAssembly = AssemblyName.GetAssemblyName(path);
Version assemblyVersion = currentAssembly.Version;

Edit: If you want to read file then you can do it like this:

string path = @"d:\AssemblyInfo.cs";
            if (File.Exists(path))
            {
                // Open the file to read from.
                string[] readText = File.ReadAllLines(path);
                var versionInfoLines = readText.Where(t => t.Contains("[assembly: AssemblyVersion"));
                foreach (string item in versionInfoLines)
                {
                    string version = item.Substring(item.IndexOf('(') + 2, item.LastIndexOf(')') - item.IndexOf('(') - 3);          
                    //Console.WriteLine(Regex.Replace(version, @"\P{S}", string.Empty));
                    Console.WriteLine(version);
                }

            }

//Output

1.0.*
1.0.0.0

Hope this help...

Tags:

C#

C# 4.0