Retrieving Assembly version from AssemblyInfo.cs file with Regex
Inside the AssemblyInfo.cs file there's this string: [assembly: AssemblyVersion("1.0.0.1")]
and I am trying to retreive one by one the numbers in it, each one is a variable in the following structure.
static struct Version
{
public static int Major, Minor, Build, Revision;
}
I am using this pattern to try to retrieve the 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 string as if it was the real match and not each number in a 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 the whole text read from the file and match.Groups[0].Value
should be "1" from the AssemblyVersion
My question is to retrieve these numbers one by one with Regex.
This small tool is to increment the application version everytime Visual Studio builds it and I know there are many tools out there to do this.
The first group is showing the full match. Your version numbers are 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, ...)
The System.Version class will do this for you. Just pass in the version string to the constructor, like so:
System.Version(this.mContents);
Also, a System.Version can be obtained by the following function calls:
Assembly.GetExecutingAssembly().GetName().Version;
The build and revision numbers can also automatically be set by specifying a '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
I hope this helps.
I stumbled on the same problem but I think it will be much easier with a slightly changed pattern.
private const string AssemblyVersionStart = @"\[assembly\: AssemblyVersion\(""(\d+\.\d+\.\d+\.\d+)""\)\]";
You get the version by parsing the Groups[1] which 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(...
Is there a reason why you must use a regexp instead of:
string[] component = this.mContents.Split('.');
bool success = int.TryParse(component[0], out Version.Major);
...
精彩评论