我有一个奇怪的问题.我想删除已加载的程序集(硬盘上的plugin.dll),但程序集被操作系统(vista)锁定,即使我已卸载它.
FE
AppDomainSetup setup = new AppDomainSetup(); setup.ShadowCopyFiles = "true"; AppDomain appDomain = AppDomain.CreateDomain(assemblyName + "_AppDomain", AppDomain.CurrentDomain.Evidence, setup); IPlugin plugin = (IPlugin)appDomain.CreateInstanceFromAndUnwrap(assemblyName, "Plugin.MyPlugins");
我还需要assemblyinfos,因为我不知道pluginassembly中的哪些类实现了IPlugin接口.在一个Pluginassembly中应该可以有多个插件.
Assembly assembly = appDomain.Load(assemblyName); if (assembly != null) { Type[] assemblyTypes = assembly.GetTypes(); foreach (Type assemblyTyp in assemblyTypes) { if (typeof(IPlugin).IsAssignableFrom(assemblyTyp)) { IPlugin plugin = (IPlugin)Activator.CreateInstance(assemblyTyp); plugin.AssemblyName = assemblyNameWithEx; plugin.Host = this; } } } AppDomain.Unload(appDomain);
如何在不锁定程序集的情况下从appDomain获取assemblyinfos?
最好的祝福
我想我已经答案了!如果您想删除已加载的程序集,则ØyvindSkaar的答案将不起作用.
代替
using (FileStream dll = File.OpenRead(path)) { fileContent = new byte[dll.Length]; dll.Read(fileContent, 0, (int)dll.Length); } Assembly assembly = appDomain.Load(fileContent);
你必须使用
byte[] b = File.ReadAllBytes(assemblyName); assembly = Assembly.Load(b);
最好的祝福
我知道这个帖子已经死了,但是我正在研究这个问题而且我得到了答案(凌晨1点30分......)
AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain app = AppDomain.CreateDomain("YaCsi", null, setup); app.DoCallBack(LoaderCallback); AppDomain.Unload(app); File.Delete("__YaCsi_Test01.dll"); static void LoaderCallback() { byte[] raw = File.ReadAllBytes("__YaCsi_Test01.dll"); Assembly yacsi = Assembly.Load(raw); ((IScript)yacsi.CreateInstance("Script")).Go(); }
它实际上不会抛出任何异常!希望有人会读到这个并且它会回答那里的问题!