[英]Retrieving Assembly version from AssemblyInfo.cs file with Regex
在AssemblyInfo.cs文件中有这个字符串: [assembly: AssemblyVersion("1.0.0.1")]
,我试图逐个检索其中的数字,每个都是以下结构中的变量。
static struct Version
{
public static int Major, Minor, Build, Revision;
}
我正在使用此模式尝试检索数字:
string VersionPattern = @"\[assembly\: AssemblyVersion\(""(\d{1,})\.(\d{1,})\.(\d{1,})\.(\d{1,})""\)\]";
但是,当我使用此代码时,结果不是预期的,而是显示完整的字符串,就好像它是真正的匹配而不是组中的每个数字。
Match match = new Regex(VersionPattern).Match(this.mContents);
if (match.Success)
{
bool success = int.TryParse(match.Groups[0].Value,Version.Major);
...
}
在这种情况下, this.mContents
是从文件读取的整个文本和match.Groups[0].Value
应该是AssemblyVersion中的“1”
我的问题是用Regex逐个检索这些数字。
这个小工具是每次Visual Studio构建它时增加应用程序版本,我知道有很多工具可以做到这一点。
第一组显示完全匹配。 您的版本号在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, ...)
System.Version类将为您执行此操作。 只需将版本字符串传递给构造函数,如下所示:
System.Version(this.mContents);
此外,可以通过以下函数调用获取System.Version:
Assembly.GetExecutingAssembly().GetName().Version;
也可以通过指定'*'自动设置构建和修订号,如下所示:
[assembly: AssemblyVersion("1.0.*")]
我希望这有帮助。
我偶然发现了同样的问题,但我认为稍微改变模式会更容易。
private const string AssemblyVersionStart = @"\[assembly\: AssemblyVersion\(""(\d+\.\d+\.\d+\.\d+)""\)\]";
您可以通过解析包含类似“1.0.237.2927”之类的Groups [1]获得版本。
try{
var match= Regex.Match(text, AssemblyVersionStart);
var version = System.Version.Parse(match.Groups[1].Value);
...
}catch(...
是否有必要使用正则表达式而不是:
string[] component = this.mContents.Split('.');
bool success = int.TryParse(component[0], out Version.Major);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.