Reflection –>get referenced assembly

Posted: May 26, 2005 in Uncategorized

I saw post in .netindiagroup and the answer i thought might be interested for some.so here goes the thread:-

The question:-

I want to get the path of the Assemblies referenced by an assembly. I’m using the following code. I’m able to get the Referenced assemblies name, But
i’m not able to get the path in which the assemblies reside(physical path). Its giving me the path of mscorlib.dll’s path, but not the path of the assemblies which i created.
 
Assembly  assembly = Assembly.LoadFrom(Path);
AssemblyName[] a =  assembly.GetReferencedAssemblies();
 
foreach(AssemblyName an in a)
{
   MessageBox.Show(an.name);  


}      
 
The answer
This is a interesting behavior you mentionmed about .Before propviding the solution let me clarify something regd ur post.First of all u r tryign to get the referenced assemblies which resides at path correct?
 
Now coming to the solution the .net reflection will use only those assemblies which you have referenced & used that is try to create an instance of the referenced assemblies access some method in constructor and its return you the name .This behavior is by design that is .net compiuler will check the config at compile time and since you didn’t have accessed the method or created the instanmce it was not showing u the asembly you are pointing at.(this is by design)
 
hope this helps .you can use any of the code u ve written or For current assembly you can use

AssemblyName[] assmbl=Assembly.GetExecutingAssembly().GetReferencedAssemblies();

foreach(AssemblyName assmblnm in assmbl )

{

MessageBox.Show(assmblnm.Name.ToString());

}

 

Another interesting point is to get teh location(physical ) of the referenced assemblies:– try assmblnm.codebase and you get ""(blank).this is due to the fact the since the same is not loaded yet you can’t get a path thus the remedy is

AssemblyName[] assmbl=Assembly.GetExecutingAssembly().GetReferencedAssemblies();

foreach(AssemblyName assmblnm in assmbl )

{Assembly asm=Assembly.load(assmblnm);

MessageBox.Show(asm.Location); //or use asm.CodeBase

}

or

For dynamically loaded assembly

string path=@"D:\vsnet20039052005\testreference\bin\Debug\testreference.dll";

Assembly assembly = Assembly.LoadFrom(path);

AssemblyName[] a = assembly.GetReferencedAssemblies();

foreach(AssemblyName an in a )

{

Assembly asm=Assembly.Load(an);

string s=asm.Location;//or use asm.CodeBase;

MessageBox.Show(s);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s