Extract all strings using Mono.Cecil in C#

First check this post on how to build and use Mono.Cecil library.

private List<String> ReadAssemblyStrings(String executable)
{
    try
    {
	if (!File.Exists(executable)) return null;
 
	AssemblyDefinition AssemblyDef = AssemblyDefinition.ReadAssembly(executable);
	List<String> sstrs = new List<String>();
 
	foreach (ModuleDefinition md in AssemblyDef.Modules)
	{
	    foreach (TypeDefinition td in md.GetTypes())
	    {
		foreach (MethodDefinition mdf in td.Methods)
		{
		    if (mdf.HasBody)
		    {
			for (int i = 0; i < mdf.Body.Instructions.Count; i++)
			{
			    Instruction id = mdf.Body.Instructions[i];
			    if (id.OpCode == OpCodes.Ldstr)
				sstrs.Add(id.Operand.ToString());
			}
  		    }
		}
    	    }
	}
	return sstrs;
    }
    catch
    {
	return null;
    }
}
%d bloggers like this: