views:

28

answers:

2

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 the Program.Main(...) function. Thanks.

+1  A: 

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:

http://stackoverflow.com/questions/502303/how-do-i-programmatically-get-the-guid-of-an-application-in-net2-0

Adam
Thanks, Adam. My search skills have been trumped! The example in the linked StackOverflow post was most helpful.
Jim Fell
A: 

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.

casperOne
Thanks, casperOne, but it's mainly to prevent the user from launching more than one instance of the application.
Jim Fell