Mac*_*iej 14 .net c# reflection
我正在寻找阅读我的应用程序使用的所有程序集(.dll)的方法.
在标准的C#项目中有"References"文件夹,当它被扩展时我可以读取所有使用的库.
我的目标是以编程方式读取我的解决方案中每个项目使用的所有程序集.
最后,我想看看我编译的*.exe应用程序使用了哪些库.
Jon*_*eet 14
你看过了Assembly.GetReferencedAssemblies
吗?
请注意,您不使用的任何引用最终都不会被发送到元数据中,因此您不会在执行时看到它们.
我之前使用GetReferencedAssemblies
递归方式来查找命名类型而不必指定程序集.
Mar*_*ell 11
要正确地执行此操作,您需要遍历程序集,获取依赖项...如果您的exe需要Dll_A,并且Dll_A需要Dll_B(即使exe不引用它),那么您的exe也需要Dll_B.
您可以通过反射查询(在任何装配上); 它需要一些工作(特别是为了防止循环引用,这确实发生 ;这是一个从"入口程序集"开始的例子,但这可以很容易地成为任何程序集:
List<string> refs = new List<string>();
Queue<AssemblyName> pending = new Queue<AssemblyName>();
pending.Enqueue(Assembly.GetEntryAssembly().GetName());
while(pending.Count > 0)
{
AssemblyName an = pending.Dequeue();
string s = an.ToString();
if(refs.Contains(s)) continue; // done already
refs.Add(s);
try
{
Assembly asm = Assembly.Load(an);
if(asm != null)
{
foreach(AssemblyName sub in asm.GetReferencedAssemblies())
{
pending.Enqueue(sub);
}
foreach (Type type in asm.GetTypes())
{
foreach (MethodInfo method in type.GetMethods(
BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic))
{
DllImportAttribute attrib = (DllImportAttribute)
Attribute.GetCustomAttribute(method,
typeof(DllImportAttribute));
if (attrib != null && !refs.Contains(attrib.Value))
{
refs.Add(attrib.Value);
}
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
refs.Sort();
foreach (string name in refs)
{
Console.WriteLine(name);
}
Run Code Online (Sandbox Code Playgroud)