C#程序编译时自动更新版本号方法
C#程序编译时自动更新版本号方法
1.创建控制台工程AutoUpdateVersion,复制如下代码,生成exe文件
using System; using System.IO; //by txwtech namespace AutoUpdateVersion { class Program { static void UpdateVersion(ref string line) { var first = line.IndexOf('"'); var second = line.LastIndexOf('"'); var sVersion = line.Substring(first + 1, second - first - 1); var arrVersion = sVersion.Split('.'); if (arrVersion.Length < 4) return; var major = Convert.ToInt32(arrVersion[0]); var minor = Convert.ToInt32(arrVersion[1]); var build = Convert.ToInt32(arrVersion[2]); var amendment = Convert.ToInt32(arrVersion[3]); if (++amendment > 999) ++build; if (build > 99) ++minor; if (minor > 9) ++major; var sNewVersion = $"{major}.{minor}.{build}.{amendment}"; line = line.Replace(sVersion, sNewVersion); Console.WriteLine("this is updateversion app"); } static void Main(string[] args) { if (args.Length != 1 || !File.Exists(args[0])) return; var lines = File.ReadAllLines(args[0]); for (int i = lines.Length - 1; i >= 0; i--) { if (lines[i].Contains("assembly: AssemblyFileVersion")) { UpdateVersion(ref lines[i]); } if (lines[i].Contains("assembly: AssemblyVersion") && !lines[i].Contains("*")) { UpdateVersion(ref lines[i]); break; } } File.WriteAllLines(args[0], lines); } } }
2. 拷贝文件
3.复制到另外一个项目,需要自动更新版本号的项目
4. 打开项目属性进行设置;
start AutoUpdateVersion $(ProjectDir)Properties\AssemblyInfo.cs
或者:
AutoUpdateVersion $(ProjectDir)Properties\AssemblyInfo.cs
欢迎讨论,相互学习。
cdtxw@foxmail.com