views:

882

answers:

3

I need to access the assembly of my project in C# .NET2.0.

I can see the GUID in the 'Assembly Information' dialog in under project properties, and at the moment I have just copied it to a const in the code. The GUID will never change, so this is not that bad of a solution, but it would be nice to access it directly. Is there a way to do this?

+1  A: 

You should be able to read the Guid attribute of the assembly via reflection. This will get the GUID for the current assembly

         Assembly asm = Assembly.GetExecutingAssembly();
        var attribs = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
        Console.WriteLine((attribs[0] as GuidAttribute).Value);

You can replace the GuidAttribute with other attributes as well, if you want to read things like AssemblyTitle, AssemblyVersion etc

You can also load another assembly (Assembly.LoadFrom and all) instead of getting the current assembly - if you need to read these attributes of external assemblies (eg - when loading a plugin)

amazedsaint
+4  A: 

Simple enough if you only want to get the Executing assembly:

using System.Reflection;

Assembly asm = Assembly.GetExecutingAssembly();
Console.WriteLine(asm.GetType().GUID.ToString());
Cerebrus
This will give you the System.Reflection.Assembly type's GUID, not his [assembly: Guid(....)]. He's looking for the GuidAttribute of his assembly. amazedsaint's and JaredPar's answers are the correct answer.
Yoopergeek
+1  A: 

Try the following code. The value you are looking for is stored on a GuidAttribute instance attached to the Assembly

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);
}
JaredPar