There's a neat little trick that you can use to never have the OS hold a lock on the .dll
's / .exe
's an .exe
needs to run.
Let's say our directory looks like this:
>opener.exe >actualProgram.exe >dependency.dll
As a basic example, we could do this:
namespace Opener
{
class Program
{
static void Main(string[] args)
{
AppDomain domain = AppDomain.CurrentDomain;
AppDomain newDomain = AppDomain.CreateDomain(
domain.FriendlyName,
domain.Evidence,
domain.BaseDirectory,
domain.RelativeSearchPath,
true, // "shadow copy" files: copy rather than lock
domain.SetupInformation.AppDomainInitializer,
domain.SetupInformation.AppDomainInitializerArguments
);
string assembly =
System.Reflection.Assembly.GetExecutingAssembly().Location
+ "\\..\\actualProgram.exe";
newDomain.ExecuteAssembly(assembly, args);
}
}
}
We could also put more logic in there, which we could use to actually replace/update actualProgram.exe
despite an instance of the process being opened. Try it: you'll be able to delete/modify/replace dependencies and the "actual" program when it's loaded via the "opener". Obviously this has its benefits, namely making updates a lot easier.
But in your "actual.exe", how can you be sure that it was loaded via another executable, and know that it was loaded without having a lock taken on the .exe
? If someone is to just load the "actual.exe", i.e. not via the "opener", I want to make sure that the process immediately exits.
Hints?