views:

568

answers:

2

Hi All, I am struggling with an issue while loading an assembly up in a temporary AppDomain to read its GetUsedReferences property. Once I do that, I call AppDomain.Unload(tempDomain) and then I try to clean up my mess by deleting the files. That fails because the file is locked. I Unloaded the temporary domain though! Any thoughts or suggestions would be greately appreciated. Here is some of my code:

//I already have btyes for the .dll and the .pdb from the actual files
AppDomainSetup domainSetup = new AppDomainSetup();
domainSetup.ApplicationBase = Environment.CurrentDirectory;
domainSetup.ShadowCopyFiles = "true";
domainSetup.CachePath = Environment.CurrentDirectory;
AppDomain tempAppDomain = AppDomain.CreateDomain("TempAppDomain", AppDomain.CurrentDomain.Evidence, domainSetup);

//Load up the temp assembly and do stuff
Assembly projectAssembly = tempAppDomain.Load(assemblyFileBuffer, symbolsFileBuffer);

//Then I'm trying to clean up
AppDomain.Unload(tempAppDomain);
tempAppDomain = null;
File.Delete(tempAssemblyFile); //I even try to force GC
File.Delete(tempSymbolsFile);

Anyway, the Deletes fail because the files are locked still. Shouldn't they be released because I Unloaded the temporary AppDomain?!?!?!

Thanks in advance,

Dan

+1  A: 

If you are reading your file like this:

FileStream assemblyFileStream = new FileStream(tempAssemblyFile, FileMode.Open);

byte[] assemblyFileBuffer = new byte[assemblyFileStream.Length];
assemblyFileStream.Read(assemblyFileBuffer, 0, (int)assemblyFileStream.Length);

your problem should be fixed if you do this:

byte[] newAssemblyBuffer = new byte[assemblyFileBuffer.Length];
assemblyFileBuffer.CopyTo(newAssemblyBuffer, 0);

and change this:

Assembly projectAssembly = tempAppDomain.Load(newAssemblyFileBuffer, symbolsFileBuffer);

Alternatively this should work as well and allow you to skip the filestream:

byte[] assemblyFileBUffer = File.ReadAllBytes(tempAssemblyFile);
David Silva Smith
+1  A: 

You have to use a Wrapper to be able to unload successfully your AppDomain. Here you can find a good example of it - http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm

GenZiy