c# - 列出 dll 中使用的命名空间

标签 c# .net namespaces

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
Finding all Namespaces in an assembly using Reflection (DotNET)



让我们考虑一下,我有 10 到 30 个 dll 的列表,我需要列出这些 dll 导入的所有命名空间。

我已经尝试使用反射作为以下代码
string[] fileEntries = Directory.GetFiles(sDir, "*.dll");
                foreach (string fileName in fileEntries)
                {
                    Assembly assembly = Assembly.LoadFrom(fileName);
                    List<string> namespaces = new List<string>();
                    foreach (var type in assembly.GetTypes())
                    {
                        string ns = type.Namespace;
                        if (!namespaces.Contains(ns))
                        {
                            namespaces.Add(ns);
                            Console.WriteLine(ns);
                        }
                    }

                }

但它只检索那些 dll 的唯一命名空间。

例如让我们考虑一个程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace sample
{
    public partial class sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string pth = filepth("D:/sample1/s.txt");
            createfile(pth);
            Response.Write("File created on path :" + pth);
        }
     }      
}

基于上面的代码它仅检索样本 但我需要检索所有命名空间 用作

**
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;

**

你能指导我吗..

等待您的宝贵意见

最佳答案

运行时没有任何命名空间。
此外,在您提供的示例中,并非使用源代码中的每个命名空间(从上下文菜单中执行“组织使用 -> 删除未使用的使用”)。

您可以查找特定程序集的引用程序集,而不是命名空间。
做你想做的事,你需要知道类型,二手 (未声明,这很容易获得!)特别是程序集的代码。

我不知道,如何在不分析 IL 代码的情况下完成它。
希望,Cecil可以帮助你......但这并不容易,也不是只有反射(reflection)的任务。

引自 MethodBody 的评论MSDN中的类:

You can use the token-resolution methods of the module class, such as ResolveType, ResolveMethod, and ResolveType, to resolve the tokens in the method body to Type objects, MethodInfo objects, and FieldInfo objects that provide detailed information about the types, methods, and fields accessed by the MSIL in the method body. Parsing method bodies requires a thorough understanding of metadata and MSIL instruction formats. Information can be found in the Common Language Infrastructure (CLI) documentation



你想自己学习 CLI 规范吗? :)

关于c# - 列出 dll 中使用的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877302/

相关文章:

c# - 如何检查 .Text 值的数组

c# - MongoDB 中的关系(使用 .Net)

.net - 覆盖 MEF 组合

c# - 将泛型转换为接口(interface)类型约束

php - 如何将我的命名空间与 PHP 中的文件夹层次结构联系起来?

c# - 消息框不显示数据库中是否有受影响的行 C# MySQL

c# - 动态创建winforms可执行文件C#

c# - UnityEngine.GameObject 与 Generic.List<UnityEngine.GameObject>

xml - 使用 XSL 根据 XML 的条件添加命名空间

.net - .Net 4.0 中命名空间声明的错误或新约定