3

I have an example method definition:

[FooAttribute("One","time")]
public void Bar(){}

Is it possible through one of the above techniques to change, for example, the argument "one" to "two" ?

Sergiu Todirascu
  • 1,367
  • 15
  • 23

1 Answers1

3

Assuming the following attribute and class:

public class MyAttribute : Attribute
{
    public MyAttribute(string a, string b)
    {
        this.a = a;
        this.b = b;
    }
    private string a,b;
}

[My("foo", "bar")]
class WithAttribute
{
}

You can use some code similar to the following (remember, this code is only for demonstration purposes and it assumes a lot of things and do no error handling at all)

var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
var type = assembly.MainModule.Types.Where(t => t.Name.Contains("WithAttribute")).Single();

var attr = type.CustomAttributes.Where(ca => ca.AttributeType.FullName.Contains("MyAttribute")).Single();

type.CustomAttributes.Remove(attr);

var newAttr = new CustomAttribute(attr.Constructor)
{ 
    ConstructorArguments = 
    {
        new CustomAttributeArgument(
             attr.ConstructorArguments[0].Type, 
             attr.ConstructorArguments[0].Value + "-Appended"),

        new CustomAttributeArgument(
             attr.ConstructorArguments[1].Type, 
             attr.ConstructorArguments[1].Value)
     }
};

type.CustomAttributes.Add(newAttr);

assembly.Write(path);
Vagaus
  • 4,174
  • 20
  • 31
  • :) Rest assured by no means this is not the most complicated code you are going to see when dealing with such type of task ;) – Vagaus Mar 14 '14 at 12:59