Getting assembly version from AssemblyInfo.cs file using Regex

Inside the AssemblyInfo.cs file there is this line: [assembly: AssemblyVersion("1.0.0.1")] , and I try to subtract the numbers in it, each of which is a variable in the following structure.

 static struct Version { public static int Major, Minor, Build, Revision; } 

I use this template to try to get numbers:

 string VersionPattern = @"\[assembly\: AssemblyVersion\(""(\d{1,})\.(\d{1,})\.(\d{1,})\.(\d{1,})""\)\]"; 

However, when I use this code, the result is not as expected, instead it shows the full line, as if it were a real match, and not every number in the group.

 Match match = new Regex(VersionPattern).Match(this.mContents); if (match.Success) { bool success = int.TryParse(match.Groups[0].Value,Version.Major); ... } 

In this case, this.mContents is all the text read from the file, and match.Groups[0].Value should be "1" from AssemblyVersion

My question is to get these numbers one by one using Regex.

This small tool consists in increasing the version of the application each time, when Visual Studio creates it, and I know that there are many tools for this.

+6
c # regex match
source share
4 answers

The first group shows a complete match. Version numbers are shown in groups 1-4:

 int.TryParse(match.Groups[1].Value, ...) int.TryParse(match.Groups[2].Value, ...) int.TryParse(match.Groups[3].Value, ...) int.TryParse(match.Groups[4].Value, ...) 
+3
source share

The System.Version class does this for you. Just pass the version string to the constructor, for example:

 System.Version(this.mContents); 

In addition, System.Version can be obtained by the following function calls:

 Assembly.GetExecutingAssembly().GetName().Version; 

Build and revision numbers can also be automatically set by specifying "*", as shown below:

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

Hope this helps.

+3
source share

I came across the same problem, but I think it will be much easier with a slightly modified template.

 private const string AssemblyVersionStart = @"\[assembly\: AssemblyVersion\(""(\d+\.\d+\.\d+\.\d+)""\)\]"; 

You get the version by analyzing groups [1] that will contain something like "1.0.237.2927".

 try{ var match= Regex.Match(text, AssemblyVersionStart); var version = System.Version.Parse(match.Groups[1].Value); ... }catch(... 
+1
source share

Is there a reason you should use regexp instead:

 string[] component = this.mContents.Split('.'); bool success = int.TryParse(component[0], out Version.Major); ... 
0
source share

All Articles