2009-05-04

AssemblyName.GetPublicKeyToken() ToString using lambda

I was searching for a convenient way to get the public key token from a signed assembly and present it in an ordinary string style that is found in all FQ assembly names. The problem is that the GetPublicKeyToken() method from the Assembly type returns a byte array and using ToString() isn’t that great.

I searched the net a bit and all I found was examples on how to do it with a loop and using ToString(”x2”) on every byte, or even more horrible, indexing the 8 bytes by hand...
But if I use a linq/lambda expression, this could be a nice one-liner? ’aye?!

Ok, first convert the byte array to a string array
GetPublicKeyToken().Select(x=>x.ToString(”x2”))
Then aggregate (i was trying the concat first, but that didn’t make any sense) to a single string.
.Aggregate((x, y) => x + y)
With some error handling this boils down to the following method.

#region public static string GetAssemblyPublickKeyToken(Assembly assembly)
/// <summary>
/// Gets the public key token of the supplied argument
/// </summary>
/// <param name="assembly">The <see cref="Assembly">to get the public key token for</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If <paramref name="assembly">is null.</exception>
public static string GetAssemblyPublickKeyToken(Assembly assembly) {
if (assembly == null) {
throw new ArgumentNullException("assembly");
}
byte[] token = assembly.GetName().GetPublicKeyToken();
if(token == null token.Length==0)
return null;
return token.Select(x => x.ToString("x2")).Aggregate((x, y) => x + y);
}
#endregion

No comments:

Post a Comment