Accessing Assembly Information GUID in a C# Form Application
I would like to use the GUID in the Assembly Information of my Microsoft Visual C# 2008 Express Edition project for use in a Mutex that is used to verify that only one instance of the application is running. How can the GUID be accessed? I only need to use it in开发者_StackOverflow社区 the Program.Main(...)
function. Thanks.
A similar question was asked on MSDN:
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/5faa901a-7e70-41f4-a096-3e6053afd5ec
Here is the code exerpt:
public static T GetAssemblyAttribute<T>(Assembly assembly) where T : Attribute
{
if (assembly == null) return null;
object[] attributes = assembly.GetCustomAttributes(typeof(T), true);
if (attributes == null) return null;
if (attributes.Length == 0) return null;
return (T)attributes[0];
}
Some of the values are also available via the Assembly
type:
How do I programmatically get the GUID of an application in .net2.0
You can call the static GetExecutingAssembly method on Assembly to get the currently executing assembly.
However, unless you have a Guid attribute associated with the assembly, you are not guaranteed to have a Guid associated with the assembly all the time.
If you do have a Guid attribute associated with the assembly, then you can take the assembly instance and call GetCustomAttributes on it and it will return the Guid attribute associated with the assembly, which you can then query for the Guid.
I would suggest, however, using the fully qualified type name of the entry point of your application as the name. It has a better semantic meaning, and is assembly-qualified, giving it a fair amount of uniqueness.
If you have concerns about someone else using that value to prevent your application from running, using a Guid isn't that much safer, someone can always reflect your assembly and get the value of the Guid.
精彩评论