2011-07-19 32 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