猿问

如何在一个dll里判断程序是否引用了另一个dll?

如题

要用try,catch做吗


喵喵时光机
浏览 958回答 2
2回答

眼眸繁星

一楼介绍了方法,我来具体化一下代码:&nbsp;你需要得到被一个特定的程序集所引用的所有程序集。这个信息可以告诉你这个程序集是否在引用一个或多个你所创建的程序集,或者你的程序集是否在引用其他特定的程序集。解决方法:使用Assembly.GetReferencedAssemblies方法去得到一个程序集所引用的程序集。例如:public&nbsp;static&nbsp;string[]&nbsp;BuildDependentAssemblyList(string&nbsp;path,&nbsp;List<string>&nbsp;assemblies) {   //&nbsp;维护一个本程序集需要的程序集列表   if&nbsp;(assemblies&nbsp;==&nbsp;null)     assemblies&nbsp;=&nbsp;new&nbsp;List<string>();  // 是否已经包含这个路径的程序了  if&nbsp;(assemblies.Contains(path) ==&nbsp;true)&nbsp;        return&nbsp;(new string[0]);&nbsp;    Assembly&nbsp;asm =&nbsp;null;  // 检查这个路径&nbsp;&nbsp;&nbsp; // 看是一个程序名还是一个路径  if&nbsp;((path.IndexOf(Path.DirectorySeparatorChar, 0, path.Length) != -1) || (path.IndexOf(Path.AltDirectorySeparatorChar, 0, path.Length) != -1)) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// 从这个路径加载程序集&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;asm =&nbsp;Assembly.ReflectionOnlyLoadFrom(path);&nbsp;&nbsp; }&nbsp;&nbsp;else&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;// 是一个程序集名称&nbsp;&nbsp;&nbsp;&nbsp;asm =&nbsp;Assembly.ReflectionOnlyLoad(path);&nbsp; }&nbsp;&nbsp;// 把程序集添加到列表中&nbsp;&nbsp;if&nbsp;(asm !=&nbsp;null)&nbsp; {  assemblies.Add(path);&nbsp; }&nbsp; // 获取所引用的程序集&nbsp; AssemblyName[] imports = asm.GetReferencedAssemblies();&nbsp; // 遍历所有的引用,并进行递归&nbsp; foreach&nbsp;(AssemblyName&nbsp;asmName&nbsp;in&nbsp;imports) {&nbsp;&nbsp;&nbsp;&nbsp; BuildDependentAssemblyList(asmName.FullName, assemblies);&nbsp; }&nbsp;&nbsp; string[] temp =&nbsp;new string[assemblies.Count];&nbsp;&nbsp; assemblies.CopyTo(temp, 0);&nbsp;&nbsp; return&nbsp;(temp);&nbsp;}&nbsp;这段代码返回一个包含有原程序集、所有其引用的程序集和这些程序集依赖的其他程序集的string数组。

一只名叫tom的猫

MSDNms-help://MS.MSDNQTR.v90.chs/fxref_mscorlib/html/2fcfa8fc-9a2b-af3a-8224-cee181149029.htmAssembly.GetReferencedAssemblies 方法
随时随地看视频慕课网APP
我要回答