Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get namespace, class, methods and its arguments with Reflection

I need to load the dll using reflection and have to get the namespace, class, methods and its arguments for that dll. Also, I need to write those information in a log file.

I have used the following code. But I got only up to class that has been written to log file.

Assembly dll = Assembly.LoadFile(@"D:\Assemblies\Myapplication.dll");
foreach (Type type in dll.GetTypes())
{
    var name = "Myapplication~" + type.FullName;
    File.AppendAllText("Assembly Details.log", "Myapplication~" + type.FullName + "\r\n\r\n");

    Console.WriteLine(type.FullName);
}

In the log file, the information needs to written as below.

Myapplication~namespace.class~method(arguments)

Eg:

Myapplication~copyassembly.class~Mymethod(String, Type)

Any suggestions would be greatly helpful.

like image 978
ManoRoshan Avatar asked Feb 09 '23 04:02

ManoRoshan


1 Answers

You can write a code similar to this

Assembly dll = Assembly.LoadFile(@"C:\YourDirectory\YourAssembly.dll");

foreach (Type type in dll.GetTypes())
{
    var details = string.Format("Namespace : {0}, Type : {1}", type.Namespace, type.Name);
    //write details to your log file here...
    Console.WriteLine(details);

    foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
    {
        var methodDetails = string.Format("{0} {1}({2})", method.ReturnParameter, method.Name, 
                                            string.Join(",", method.GetParameters().Select(p => p.ParameterType.Name)));
        //write methodDetails to your log file here...
        Console.WriteLine("\t" + methodDetails);
    }
}

Which will write these details

Namespace : MyNamespace.Helpers, Type : Constants
    System.String  ToString()
    Boolean  Equals(Object)
    Int32  GetHashCode()
    System.Type  GetType()
Namespace : MyNamespace.Helpers, Type : FileHelper
    Void  WriteToFile(String,String,String,String)
    Void  UpdateFile(String,String,Boolean)

Here, you might [1] change the BindingFlags as per your need [2] change format of the log string (details/methodDetails) [3] format collection/generic types as you need

Edit
If you want to display without the return type, simply format it like

var methodDetails = string.Format("{1}({2})", 
                                  method.Name, 
                                  string.Join(",", method.GetParameters().Select(p => p.ParameterType.Name)));
like image 75
Arghya C Avatar answered Feb 11 '23 01:02

Arghya C