是否有一种方法可以安全地使用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);
但是如果目录不存在会抛出异常,我想忽略这个错误。
如果抛出异常显然不会。只要在运行MEF容器安装程序之前创建目录,就不会抛出错误。
根据文档:
路径必须为
AppDomain.BaseDirectory
的绝对路径或相对路径。
PsuedoCode执行目录检查:
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);