Jump to content
Tuts 4 You

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


r3xq1

Recommended Posts

Posted
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 ?

 

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
Posted

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
  • 2 weeks later...
Posted (edited)
On 4/2/2021 at 7:50 PM, kao said:

Very simple example, just to show the idea..

It worked great!
And how can you find a constant not by a field but by an object of type string?

public const string Test = "{ConstText}";

I can find the constant I need by the field name

field.Name.String.Contains("Test")

But how to find by name: {ConstText}

 

I already figured it out myself))

You just need to check the value:

if (field.HasConstant && field.Constant.Value.Equals("{ConstText}"))

----------

Why if you try to output to the console

Console.WriteLine(Test);


Changed, then it shows the default text that was set in it Out: {ConstText}  ???

Edited by r3xq1
  • 2 weeks later...
Posted

So how do you fix the problem? who knows?

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...