Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the Version number from a AssemblyInfo.cs file

Tags:

c#

c#-4.0

I'm trying to extract the version number from a AssemblyInfo.cs file! And I'm trying to use System.Reflection.Assembly.LoadFile(path); But while doing this I get a BadImageFormatException; "The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)". So now I wounder, is that not a possible way to go about it? And should I use RegEx instead?

I have read many examples with GetExecutingAssembly() but I do want to get the version from an other project.

Clarification: I want to read the version info from the AssemblyInfo.cs file! And not from a compiled file. I'm trying to make a tool to update my version numbers before I make a new release.

like image 391
Markus Avatar asked May 08 '12 12:05

Markus


1 Answers

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...

like image 188
Niranjan Singh Avatar answered Sep 21 '22 21:09

Niranjan Singh