【问题标题】:Whats the best way to programmatically read ildasm output以编程方式读取 ildasm 输出的最佳方法是什么
【发布时间】:2017-03-08 18:18:04
【问题描述】:

我正在尝试使 ildasm 输出更像 json 或 xml,以便以编程方式读取它有点容易。

我打算这样做的方式是逐行读取输出,然后将类和方法等添加到列表中,然后将其修改并重写为xml,然后读取它。

问题:有没有更聪明或更简单的方法来读取输出?

【问题讨论】:

  • 举个例子输出和你想用它做什么。目前我无法在 thisthis 重复(或只是 broad vs unclear)之间进行选择。
  • 为什么要通过 ildasm?直接阅读二进制文件似乎更容易。 Cecil 是一个可能会有所帮助的库。 github.com/jbevain/cecil/wiki
  • ildasm 输出不应被ilasm 以外的任何东西以编程方式读取。那就是疯狂。

标签: c# ildasm


【解决方案1】:

有一种方法可以通过阅读 IL 代码来获取类和方法的列表。 我所说的解决方案可能有点长,但它会起作用。

IL 只不过是 .exe 或 .dll 。首先尝试使用 ILSpy 将其转换为 C# 或 VB。下载此工具并在其中打开您的 DLL。该工具可以将您的 IL 代码转换为 C# 或 VB。

转换后,将转换后的代码保存为txt文件。

然后读取文本文件,找到里面的类和方法。

读取方法名称:

   MatchCollection mc = Regex.Matches(str, @"(\s)([A-Z]+[a-z]+[A-Z]*)+\(");

读取类名:

逐行遍历文件并检查该行是否具有名称 "Class" 。如果它具有名称,则拆分值并存储名称 "Class" 之后的值/文本,该名称只不过是 ClassName

完整代码:

  static void Main(string[] args)
    {
        string line;
        List<string> classLst = new List<string>();
        List<string> methodLst = new List<string>();
        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\******\Desktop\TreeView.txt");
        string str = File.ReadAllText(@"C:\Users\*******\Desktop\TreeView.txt");

        while ((line = file.ReadLine()) != null)
        {      
                if (line.Contains("class")&&!line.Contains("///"))
                {
                    // for finding class names

                    int si = line.IndexOf("class");
                    string followstring = line.Substring(si);
                    if (!string.IsNullOrEmpty(followstring))
                    {
                        string[] spilts = followstring.Split(' ');

                        if(spilts.Length>1)
                        {
                            classLst.Add(spilts[1].ToString());
                        }

                    }
                }
        }
        MatchCollection mc = Regex.Matches(str, @"(\s)([A-Z]+[a-z]+[A-Z]*)+\(");

        foreach (Match m in mc)
        {
            methodLst.Add(m.ToString().Substring(1, m.ToString().Length - 2));
            //Console.WriteLine(m.ToString().Substring(1, m.ToString().Length - 2));
        }

        file.Close();
        Console.WriteLine("******** classes ***********");
        foreach (var item in classLst)
        {
            Console.WriteLine(item);
        }
        Console.WriteLine("******** end of classes ***********");

        Console.WriteLine("******** methods ***********");
        foreach (var item in methodLst)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("******** end of methods ***********");
        Console.ReadKey();

    }

这里我将类名和方法名存储在一个列表中。您可以稍后将它们存储在 XML 或 JSON 中,如上所述。

如果您遇到任何问题,请联系我们。

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2010-11-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2014-12-01
    • 2010-09-24
    相关资源
    最近更新 更多