Jump to content
Tuts 4 You

[C#, Dnlib] How do I change const string?


Recommended Posts

r3xq1
public const string Test = "{ConstText}";

And Found Const

using (var module = ModuleDefMD.Load(Resources.Stub))
{
  foreach (var type in module.GetTypes().Where(t => t.HasMethods))
  {
    IList<FieldDef> fieldstr = type.Fields;
    for (int i = 0; i < fieldstr.Count; i++)
    {
       // fieldstr[i].Name - This found const string
    }
}

How to change ?

 

Link to post
r3xq1
Posted (edited)
7 hours ago, XenocodeRCE said:

It's a FieldDef, not a MethodDef

So I'm looking in FieldDef and not MethodDef. How do I replace a string?

 

foreach (var type in module.GetTypes())
{
    IList<FieldDef> fieldstr = type.Fields;
    for (int i = 0; i < fieldstr.Count; i++)
    {
       // fieldstr[i].Name - This found const string
    }
}

 

Edited by r3xq1 (see edit history)
Link to post
kao

Very simple example, just to show the idea..

        static void Main(string[] args)
        {
            using (var module = ModuleDefMD.Load(args[0]))
            {
                foreach (var type in module.GetTypes())
                {
                    foreach (FieldDef field in type.Fields)
                    {
                        // this will change all string constant values to "kao". Make sure to fix the `if`!!!
                        if (field.HasConstant && field.ElementType == ElementType.String)
                        {
                            field.Constant.Value = "kao";
                        }
                    }
                }
                module.Write(args[1]);
            }
        }

 

  • Like 4
Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...