2011-04-13 22 views
4

我有一些WCF服务,并且在某个文件夹内的程序集中有一个服务合约(接口)列表。我知道的命名空间,它会是这个样子:C# - 从程序集中的文件夹中获取所有接口

MyProject.Lib.ServiceContracts 

我希望有一种方法能够抓住所有的文件夹内,这样我就可以遍历每一个抢的属性关每个方法。

以上可能吗?如果是这样,关于如何做到上述的任何建议?

感谢您的任何帮助。

回答

13

这应该让你所有这些接口

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()) 
      { 
       // .... 

      } 
     } 
    } 
+1

柜面的DLL是不是一个CLR程序集,最好默默地处理负载例外。 – 2011-04-13 13:54:18

+0

完美!因为我知道程序集名称,所以我可以稍微将其缩小一点,但其余部分对我来说非常合适。 – Brandon 2011-04-13 14:07:33

+0

DirectoryInfo和FileInfo对象的权重较轻,在某些情况下,安全检查可能会绕过相应的目录和文件类别。 http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.IO.DIRECTORYINFO);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22 ); K(DevLang-CSHARP)RD =真 – 2011-04-13 14:10:37

1

@Aliostad答案已经发布,但我会添加我的还有我觉得它有点更彻底......

// 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; 

      } 
0

以上答案可能无法正确使用C++/CLI创建的程序集(即,具有托管/非托管代码的程序集)。

我建议将下面一行:

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

这一行:

foreach (Type ti in assembly.GetExportedTypes().Where(x=>x.IsInterface)) 
相关问题