C# .NET 2.0 でプロジェクトのアセンブリにアクセスする必要があります。
プロジェクトのプロパティの下にある [アセンブリ情報] ダイアログで GUID を確認できます。現時点では、それをコードの const にコピーしました。GUID は決して変更されないため、これはそれほど悪い解決策ではありませんが、直接アクセスできると便利です。これを行う方法はありますか?
C# .NET 2.0 でプロジェクトのアセンブリにアクセスする必要があります。
プロジェクトのプロパティの下にある [アセンブリ情報] ダイアログで GUID を確認できます。現時点では、それをコードの const にコピーしました。GUID は決して変更されないため、これはそれほど悪い解決策ではありませんが、直接アクセスできると便利です。これを行う方法はありますか?
次のコードを試してください。探している値は、Assembly にアタッチされた GuidAttribute インスタンスに格納されます
using System.Runtime.InteropServices;
static void Main(string[] args)
{
var assembly = typeof(Program).Assembly;
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];
var id = attribute.Value;
Console.WriteLine(id);
}
Another way is to use Marshal.GetTypeLibGuidForAssembly.
According to MSDN:
When assemblies are exported to type libraries, the type library is assigned a LIBID. You can set the LIBID explicitly by applying the System.Runtime.InteropServices.GuidAttribute at the assembly level, or it can be generated automatically. The Tlbimp.exe (Type Library Importer) tool calculates a LIBID value based on the identity of the assembly. GetTypeLibGuid returns the LIBID that is associated with the GuidAttribute, if the attribute is applied. Otherwise, GetTypeLibGuidForAssembly returns the calculated value. Alternatively, you can use the GetTypeLibGuid method to extract the actual LIBID from an existing type library.
リフレクションを介してアセンブリの GUID 属性を読み取ることができるはずです。これにより、現在のアセンブリの GUID が取得されます
Assembly asm = Assembly.GetExecutingAssembly();
object[] attribs = asm.GetCustomAttributes(typeof(GuidAttribute), true);
var guidAttr = (GuidAttribute) attribs[0];
Console.WriteLine(guidAttr.Value);
AssemblyTitle、AssemblyVersion などを読みたい場合は、GuidAttribute を他の属性に置き換えることもできます。
外部アセンブリのこれらの属性を読み取る必要がある場合 (たとえば、プラグインをロードするとき) は、現在のアセンブリを取得する代わりに、別のアセンブリ (Assembly.LoadFrom およびすべて) をロードすることもできます。
すぐに使える実用的な例として、これは以前の回答に基づいて最終的に使用したものです。
using System.Reflection;
using System.Runtime.InteropServices;
label1.Text = "GUID: " + ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value.ToUpper();
または、この方法で静的クラスから使用できます。
/// <summary>
/// public GUID property for use in static class </summary>
/// <returns>
/// Returns the application GUID or "" if unable to get it. </returns>
static public string AssemblyGuid
{
get
{
object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
if (attributes.Length == 0) { return String.Empty; }
return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value.ToUpper();
}
}