C # - get all interfaces from a folder in an assembly

I have some WCF services, and I have a list of service contracts (interfaces) in the assembly in a specific folder. I know the namespace and will look something like this:

MyProject.Lib.ServiceContracts 

I was hoping you could capture all the files in this folder so that I could iterate over them and retrieve the attributes of each method.

Is it possible? If so, any tips on how to do this?

Thanks for any help.

+4
source share
3 answers

This should provide you with all of these interfaces :

  string directory = "/"; foreach (string file in Directory.GetFiles(directory,"*.dll")) { Assembly assembly = Assembly.LoadFile(file); foreach (Type ti in assembly.GetTypes().Where(x=>x.IsInterface)) { if(ti.GetCustomAttributes(true).OfType<ServiceContractAttribute>().Any()) { // .... } } } 
+13
source

@ The answer to Aliostad has already been published, but I will add my own, and also believe that this is a little more thorough ...

 // add usings: // using System.IO; // using System.Reflection; public Dictionary<string,string> FindInterfacesInDirectory(string directory) { //is directory real? if(!Directory.Exists(directory)) { //exit if not... throw new DirectoryNotFoundException(directory); } // set up collection to hold file name and interface name Dictionary<string, string> returnValue = new Dictionary<string, string>(); // drill into each file in the directory and extract the interfaces DirectoryInfo directoryInfo = new DirectoryInfo(directory); foreach (FileInfo fileInfo in directoryInfo.GetFiles() ) { foreach (Type type in Assembly.LoadFile(fileInfo.FullName).GetTypes()) { if (type.IsInterface) { returnValue.Add(fileInfo.Name, type.Name); } } } return returnValue; } 
+1
source

The above answers may not work correctly for collectors created using C ++ / CLI (for example, assemblies with managed / unmanaged code).

I suggest replacing this line:

 foreach (Type ti in assembly.GetTypes().Where(x=>x.IsInterface)) 

with this line:

 foreach (Type ti in assembly.GetExportedTypes().Where(x=>x.IsInterface)) 
0
source

Source: https://habr.com/ru/post/1347913/


All Articles