Thursday, August 21, 2008

How to get C# Assembly GUID

How to get C# Assembly GUID using Reflection




public string AssemblyGuidString(System.Reflection.Assembly assembly)
{
object[] objects =
assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
if (objects.Length > 0)
{
return ((System.Runtime.InteropServices.GuidAttribute)objects[0]).Value;
}
else
{
return String.Empty;
}
}






keys: c#, assembly, reflection, guid, attributes

6 comments:

Anonymous said...

Is this a joke or what? You CANNOT use GetExecutingAssembly() from an instance, and you can't use string return type for a void method!

M.I. said...

No joke, it's typo. Now everything is ok. Thanks for your comment.

Anonymous said...

"you CANNOT use GetExecutingAssembly()"

Why not?

I'm using GetExecutingAssembly in my code and it works fine...

as in: Assembly.GetExecutingAssembly().GetName().Version.ToString();

Anonymous said...

cartoon, Assembly is class not an instance. dumb

Anonymous said...

But 'GetExecutingAssembly()' gets the assembly representing the assembly that contains the code that is currently executing... yeah, really dumb...

Anonymous said...

Solution:

public string AssemblyGuidString()
{
object[] arr = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);

if (arr.Length > 0)
{
return ((System.Runtime.InteropServices.GuidAttribute)arr[0]).Value;
}
else
{
return String.Empty;
}
}