开发者

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 an assembly within a certain folder. I know the namespace and it will look something like this:

MyProject.Lib.ServiceContracts

I was hoping there was a way to be abl开发者_如何学运维e to grab all files within that folder so I can iterate over each one and grab the attributes off of each method.

Is the above possible? If so, any advice on how to do the above?

Thanks for any assistance.


This should get you all such 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())
            {
                // ....

            }
        } 
    }


@Aliostad answer is already posted, but I will add mine as well as I think it a bit 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;

          }


The above answers may not work correctly for Assemblies created with C++/CLI (i.e. an assembly with both 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜