C# で製品バージョンとかファイルバージョンをAssemblyInfoから取得する

C#でコマンド作っててUsageの表示でバージョンとか出したいけど、AssemblyInfo.csに書いてあることを2度書きたくなかったので

  • Command Line Parser Libraryを使ってUsageを表示しているので、その中でアセンブリ情報を取得して表示します。

製品バージョンとファイルバージョン

  • 意外と簡単。
using System.Reflection;
using System.Diagnostics;

FileVersionInfo ver = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
help.Heading = new HeadingInfo(
          string.Format("foo Ver. {0} (File Ver. {1})", ver.ProductVersion, ver.FileVersion));

Copyright

  • 若干わかりにくい
using System.Reflection;

AssemblyCopyrightAttribute copyright = Assembly.GetExecutingAssembly().GetCustomAttributes(
               typeof(AssemblyCopyrightAttribute), false)[0] as AssemblyCopyrightAttribute;
help.Copyright = copyright.Copyright;

全体

using CommandLine;
using CommandLine.Text;

[HelpOption]
public string GetUsage()
{
    var help = new HelpText();

    FileVersionInfo ver = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
    help.Heading = new HeadingInfo(string.Format("foo Ver. {0} (File Ver. {1})", ver.ProductVersion, ver.FileVersion));

    AssemblyCopyrightAttribute copyright = Assembly.GetExecutingAssembly().GetCustomAttributes(
              typeof(AssemblyCopyrightAttribute), false)[0] as AssemblyCopyrightAttribute;
    help.Copyright = copyright.Copyright;

    help.AddDashesToOption = true;

    help.AddPreOptionsLine("Usage: foo [ -a/--aaa | -b/--bbb ]");

    return help;
}
  • この辺を参考にしました

u-prog.cocolog-nifty.com