views:

63

answers:

2

I have a .NET assembly DLL that is created on-the-fly from pre-compiled code in a database. Is there a way to create the DLL file, put data into it, load it with the Assembly class, then when the process exits, have that DLL be deleted?

My first thoughts were to open it with the FILE_SHARE_DELETE flag, load it with Assembly.LoadFrom, and have it automatically be deleted.

Although LoadLibrary does open files with the FILE_SHARE_DELETE flag, when the DLL is still mapped in memory, the OS will not delete the file.

So, how can the DLL be deleted when the process exits without using AppDomains or starting external "delete this file after target process exits" executables (the .NET DLLs that load at runtime depend on user input, so doing this would involve some kind of process communication, which I would like to avoid).

A: 

If you keep track of where the assembly is compiled & saved to, you can just use File.Delete on the location (Located in System.IO)

Tommy
A: 

No, that can't work. The CLR creates a memory mapped file view on the DLL, it can't be deleted until that view is destroyed. Which won't happen until the AppDomain is unloaded. Since you're probably loading it in the primary AD, that won't happen until the program stops running.

A helper process that starts your main one and deletes the DLL after it stops running is about all I can think of if you don't want to use an AD.

Hans Passant