2011-07-19 34 views
9

有没有办法安全地使用DirectoryCatalog来处理目录是否存在?MEF和DirectoryCatalog

这里我的容器是如何建立一个代码示例:

//Create an assembly catalog of the assemblies with exports 
    var catalog = new AggregateCatalog(
     new AssemblyCatalog(Assembly.GetExecutingAssembly()), 
     new AssemblyCatalog(Assembly.Load("My.Second.Assembly")), 
     new DirectoryCatalog("Plugins", "*.dll")); 

    //Create a composition container 
    var container = new CompositionContainer(catalog); 

但是,如果目录不存在抛出一个异常,我想忽略这个错误。

+1

有没有,你不能只检查用于设置'AggregateCatalog'之前所在的目录存在的理由? –

+0

我会的,但似乎有一些很好的逻辑内置到DirectoryCatalog中以获取正确的路径(不仅仅是当前目录)。任何人都知道它的用途? Assembly.Location? – jonathanpeppers

+0

我对下面的答案进行了评论,但我在这里也会提到它......你不应该仅仅依靠检查目录的存在。你应该考虑到你想要处理的任何IOException(例如,如果Directory不存在,或者文件被锁定或UAT等) –

回答

9

显然不是如果引发异常。只需在运行MEF容器设置之前创建目录,然后不会抛出错误。

根据the documentation

的路径必须是绝对的或相对AppDomain.BaseDirectory

伪码做目录检查:

string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); 

    //Check the directory exists 
    if (!Directory.Exists(path)) 
    { 
     Directory.CreateDirectory(path); 
    } 

    //Create an assembly catalog of the assemblies with exports 
    var catalog = new AggregateCatalog(
     new AssemblyCatalog(Assembly.GetExecutingAssembly()), 
     new AssemblyCatalog(Assembly.Load("My.Other.Assembly")), 
     new DirectoryCatalog(path, "*.dll")); 

    //Create a composition container 
    _container = new CompositionContainer(catalog); 
+0

请参阅我上面的评论。 DirectoryCatalog使用什么方法来扩展完整路径? – jonathanpeppers

+0

它是绝对的或相对于System.AppDomain.BaseDirectory。 –

+0

标记为答案。我在你的答案中更新了你的代码。 – jonathanpeppers