在 WinForms/WPF 菜單「幫助 → 關於」中顯示程序集版本號,自動同步編譯版本。
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;
public void ShowAbout() {
// 方式一:FileVersionInfo(推薦,包含文件版本、產品版本、公司等元數據)
var fvi = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
string version = fvi.FileVersion; // 如 "1.2.3.4"
string product = fvi.ProductName;
string copyright = fvi.LegalCopyright;
// 方式二:Assembly(僅程序集版本)
// var asm = Assembly.GetExecutingAssembly();
// var name = asm.GetName().Version.ToString();
MessageBox.Show($"{product} v{version}\n{copyright}", "關於", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
在 AssemblyInfo.cs 中:
[assembly: AssemblyVersion("1.0.*")]
// 自動生成:主版本.次版本.構建號(從2000/1/1起天數).修訂號(從午夜起秒數/2)
或使用 MSBuild 任務 / GitVersion 根據語義化版本規範自動賦值。
var fvi = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
lblVersion.Content = $"Version {fvi.FileVersion}";