Search code examples
c#attributesregistrymetadata

How do I turn a c# attribute into a text content?


I have a solution with several C# class libraries that are plugins in a larger system. This system registers its plugins in Windows' registry. What I would like to do is describe the registry keys in a way that can be extracted from the compiled DLLS and then put into a text (.reg) file, preferably as part of the build process.

Is there a predefined attribute for this type of metadata? And is there a command line tool or MSBuild task that can extract them?


Solution

  • Imagine this attribute

    [System.AttributeUsage(System.AttributeTargets.Class,
                       AllowMultiple = true)  // Multiuse attribute.]
    public class RegistryKey : System.Attribute
    {
        public string Name {get; private set;}
        public string Type {get; private set;}
        public string Data {get; private set;}
    
        public RegistryKey(string name, string type, string data)
        {
            Name = name;
            Type = type;
            Data = data;
        }
    }
    

    Consume it with reflection like this

    var attrs = System.Attribute.GetCustomAttributes(typeof(MahClass));
    foreach (var attr in attrs)
    {
        if (attr is RegistryKey)
        {
            var name = attr.Name;
            ...
        }
    }